Should I use [innerHTML] or the usual way (Angular 2)
Asked Answered
J

2

15

I have my example: string; in my component.ts file. I can output this variable in two ways (at least that I know of):

I can do:

<p>{{ example }}</p>

and I can do:

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

Well, when I use the first way, my IDE (phpStorm) tells my that my var is unnecessary because I never used it. But when I use the second way, it says I'm using it.

Does it matter which method should I use?

Janeejaneen answered 20/6, 2016 at 21:28 Comment(4)
the first way could cause the user to see the literal string "{{ example }}" for a brief moment if the page loads before example is set. the second method is better for this reason.Zischke
Even when I use Angular 2?Janeejaneen
afaik, unless example is actual html, you should use the first way. innerHTML is for actual html markupIncredulous
Possible duplicate of How to get angular2 [innerHtml] to workKilbride
I
14

Per the Angular 2 docs: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#property-binding-or-interpolation-

There is no technical reason to prefer one form to the other. We lean toward readability, which tends to favor interpolation. We suggest establishing coding style rules and choosing the form that both conforms to the rules and feels most natural for the task at hand.

And, as far as being concerned about innerHTML having malicious scripts in it (another reason you might favor interpoliation):

Fortunately, Angular data binding is on alert for dangerous HTML. It sanitizes the values before displaying them.

So, really it's up to you. Angular team says they favor {{ example }} because it's easier to read, and I tend to agree with them, but seems like you can go either way.

Incredulous answered 20/6, 2016 at 21:41 Comment(2)
In IE Edge 41.16299.15.0 "null" displays when using innerHTML on a field that is not defined. It does not show if you use interpolation or innerText.Dvorak
@Dvorak I'm having the same issue in IE11 and would like to know if anyone has found a solution.Diadem
M
8

My IDE has the same limitation as yours and it's annoying. Be careful though, the two options you presented are not the same. If you want to render HTML markup (to add DOM elements to the page), use:

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

If you expect to output just strings, do not bind to this property. Either use interpolation:

<p>{{ example }}</p>

Or bind to the innerText:

<p [innerText]="example"></p>

To prove that they're different, in the Component, set:

example = '<h3>Am I big?</h3>'

Then in your template, have both divs:

<p [innerText]="example"></p>
<p [innerHTML]="example"></p>

You'll see that the paragraphs render differently :-)

Mahon answered 21/6, 2016 at 1:15 Comment(1)
This should be the accepted answer. NOTE: in case of [innerHTML], you have to use "encapsulation: ViewEncapsulation.None" in @Component, and that is the worst part! :-(Lipsey

© 2022 - 2024 — McMap. All rights reserved.