Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 313
Eliya Cohen Avatar asked Jun 20 '16 21:06

Eliya Cohen


2 Answers

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.

like image 87
Rob Louie Avatar answered Oct 23 '22 13:10

Rob Louie


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 :-)

like image 6
BeetleJuice Avatar answered Oct 23 '22 12:10

BeetleJuice