我应该使用 [innerHTML] 还是通常的方式 (Angular 2)
Should I use [innerHTML] or the usual way (Angular 2)
我的 example: string;
在我的 component.ts
文件中。我可以用两种方式输出这个变量(至少我知道):
我能做到:
<p>{{ example }}</p>
我能做到:
<p [innerHTML]="example"></p>
好吧,当我使用第一种方式时,我的 IDE (phpStorm) 告诉我,我的 var 是不必要的,因为我从未使用过它。但是当我使用第二种方式时,它说我正在使用它。
我应该使用哪种方法重要吗?
根据 Angular 2 个文档:
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.
并且,就担心 innerHTML 有恶意而言
其中的脚本(您可能喜欢插值的另一个原因):
Fortunately, Angular data binding is on alert for dangerous HTML. It
sanitizes the values before displaying them.
所以,真的取决于你。 Angular 团队说他们喜欢 {{ example }}
因为它更容易阅读,我倾向于同意他们的观点,但似乎你可以选择任何一种方式。
我的 IDE 和你的有同样的限制,这很烦人。不过要小心,您提供的两个选项并不相同。如果要呈现 HTML 标记(向页面添加 DOM 元素),请使用:
<p [innerHTML]="example"></p>
如果您希望只输出字符串,不要绑定到这个属性。要么使用插值:
<p>{{ example }}</p>
或绑定到 innerText
:
<p [innerText]="example"></p>
为了证明它们是不同的,在组件中,设置:
example = '<h3>Am I big?</h3>'
然后在你的模板中,有两个 div:
<p [innerText]="example"></p>
<p [innerHTML]="example"></p>
您会看到段落呈现不同 :-)
我的 example: string;
在我的 component.ts
文件中。我可以用两种方式输出这个变量(至少我知道):
我能做到:
<p>{{ example }}</p>
我能做到:
<p [innerHTML]="example"></p>
好吧,当我使用第一种方式时,我的 IDE (phpStorm) 告诉我,我的 var 是不必要的,因为我从未使用过它。但是当我使用第二种方式时,它说我正在使用它。
我应该使用哪种方法重要吗?
根据 Angular 2 个文档: 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.
并且,就担心 innerHTML 有恶意而言 其中的脚本(您可能喜欢插值的另一个原因):
Fortunately, Angular data binding is on alert for dangerous HTML. It sanitizes the values before displaying them.
所以,真的取决于你。 Angular 团队说他们喜欢 {{ example }}
因为它更容易阅读,我倾向于同意他们的观点,但似乎你可以选择任何一种方式。
我的 IDE 和你的有同样的限制,这很烦人。不过要小心,您提供的两个选项并不相同。如果要呈现 HTML 标记(向页面添加 DOM 元素),请使用:
<p [innerHTML]="example"></p>
如果您希望只输出字符串,不要绑定到这个属性。要么使用插值:
<p>{{ example }}</p>
或绑定到 innerText
:
<p [innerText]="example"></p>
为了证明它们是不同的,在组件中,设置:
example = '<h3>Am I big?</h3>'
然后在你的模板中,有两个 div:
<p [innerText]="example"></p>
<p [innerHTML]="example"></p>
您会看到段落呈现不同 :-)