Search code examples
polymerweb-componentpolymer-3.x

Inject HTML with Polymer 3


I want to add some HTML formatted text to a template in Polymer 3. This HTML comes from a function (which gets the string from a translation file using 'localize'), like:

This is <sup>®</sup> text.

The only way that I found to do this, is by adding a DIV tag to the template with some class (myText value comes from function):

return html`
  <div class="marker">[[myText]]</div>
`;

...and then in the ready() function, query this element and changing its innerHTML and replacing the text (in this case ®) by surrounding it with <sup> tag:

ready() {
      super.ready();             

      var me = this;
      setTimeout(function(){
        var elements = me.shadowRoot.querySelectorAll(".marker");           
        elements.forEach(element => {
          element.innerHTML = element.innerHTML.replace("®","<sup>®</sup>");          
        });
      },500);
  }

This works, but I don't like the timeout approach, as I will never be sure that it will always work and you see the changes with a small delay.

The reason that I use the timeout however, is because I don't find any lifecycle event in which I'm sure that all elements have been rendered and available. For example, if I use dom-if, those elements are not rendered yet in the ready() event; and so I get back 'null' from querySelectorAll.

So my question is: is there another way (so not using the timeout approach) to add a HTML formatted string (that comes from a function) to an element in the template?


Solution

  • Solution was actually quite simple:

    return html`
      <div inner-h-t-m-l="[[myText]]"></div>
    `;