Search code examples
htmlpolymerweb-componentpolymer-2.x

Inject HTML from function


I following the 'Quick tour of Polymer' and there is a section that explain us how to repeat element based on an array, but it only show us how to do it with a template repeater, and I don't really know how its work from behind. I tried to do my own repeater but Polymer inject my code as a string, like unescape characters.

code:

<dom-module id="employee-list">

<template>
    [[employe()]]
</template>

<script>

    class EmployeeList extends Polymer.Element {

      static get is () {

        return 'employee-list'

      }

      constructor () {
        super()
        this.employees = [
          {first: 'Bob', last: 'Li'},
          {first: 'Ayesha', last: 'Johnson'},
          {first: 'Fatma', last: 'Kumari'},
          {first: 'Tony', last: 'Morelli'}
        ]
      }

      employe(employees = this.employees) {

        let template = '<div>Employee List</div>'
        template += employees.map((currentEmployee, id) => {
          return  `<div>Employee ${id}, FullName : ${currentEmployee.first + ' ' + currentEmployee.last}</div>`
        })

        return template

      }


    }

    customElements.define(EmployeeList.is,EmployeeList)

</script>

</dom-module>

result:

<div>Employee List</div><div>Employee 0, FullName : Bob Li</div>,<div>Employee 1, FullName : Ayesha Johnson</div>,<div>Employee 2, FullName : Fatma Kumari</div>,<div>Employee 3, FullName : Tony Morelli</div>

And I would like to know if its a form of inject unescape characters / html in Polymer@2


Solution

  • You can use a querySelector within your function to make that happen

    html

    <template>
        <div id="employee-list"></div>
    </template>
    

    js

    this.querySelector("#employee-list").innerHTML = template
    

    As mentioned by Jordan, you should use dom-repeat

    <div> Employee list: </div>
    <template is="dom-repeat" items="{{employees}}">
        <div>First name: <span>{{item.first}}</span></div>
        <div>Last name: <span>{{item.last}}</span></div>
    </template>
    

    If you are doing it the way you are to get an id there is an alternative using dom-repeat. You could use the attribute index-as to do that.

    <template is="dom-repeat" items="{{employees}}" index-as="id">
    

    You can find out more about dom-repeat here: https://www.polymer-project.org/1.0/docs/api/dom-repeat