Eliya Cohen Eliya Cohen - 1 year ago 134
Javascript Question

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

I have my

example: string;
in my
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download