1

In an Ionic2 application, I want to render <ion-icon>s contained in an HTML string. The HTML string could be something along the lines of:

public explanation = "To open the menu, click the <ion-icon name='menu'></ion-icon> icon to the top left.";

The strings are stored in a translation file. When being output, I know that HTML strings are escaped by default and I tried to output the string with to prevent sanitization:

<p [innerHTML]="explanation"></p>

Problem: Now the <ion-icon> code is not escaped, but the icon does not render either (even though the node is present in the DOM). The code works well when using regular HTML like <b> tags.

Dynamic template evaluation?

I suspect the behavior is due to the fact that the code is directly inserted into the DOM and not evaluated by Ionic/Angular. For Angular1 there has been a large discussion here on SO. Solutions for Angular2 I have seen so far use the deprecated DynamicComponentLoader or are fairly complex.

Is there any easy solution to showing the icon? Defining two translation strings ...LEFT_OF_ICON and ...RIGHT_OF_ICON would work in this case, but feels a bit awkward.

Community
  • 1
  • 1
Fabian Kleiser
  • 2,988
  • 3
  • 27
  • 44

1 Answers1

1

Angular treats HTML added using [innerHTML]="..." as plain HTML and just adds it to the DOM without processing it in any way (no bindings, not directive or component instantiation).

You can use ViewContainerRef.createComponent() instead.

See Angular 2 dynamic tabs with user-click chosen components for an example.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • In the Plunker mentioned in the linked answer I can see that you need to pass a component factory of a specific component: `this.viewContainerRef.createComponent(this.componentFactory, 0);`. As in this case the component is used with its tag inside the HTML string, I cannot simply use this approach, right? – Fabian Kleiser Aug 29 '16 at 13:54
  • There is some support for CSS selectors but I haven't seen working examples. You need to create a component with that HTML in it's template, then you can add that component dynamically. This might be related http://stackoverflow.com/questions/36008476/how-to-realize-website-with-hundreds-of-pages-in-angular2 – Günter Zöchbauer Aug 29 '16 at 13:58