Why use apostrophe for variables in Angular 4

喜夏-厌秋 提交于 2019-12-23 04:51:09

问题


I want to know about the difference between these two lines.

<p [myHighlight]="'yellow'">Highlighted in yellow</p>
<p myHighlight="orange">Highlighted in orange</p>

myHighlight is custom directive where all tags inside it will be set custom color. Thanks.


回答1:


Have a read of this page on the angular docs it will tell you all about the template syntax.

But simply the top row will be evaluated as an expression and the line below as a constant.

Quoted from the docs.

The brackets tell Angular to evaluate the template expression. If you omit the brackets, Angular treats the string as a constant and initializes the target property with that string. It does not evaluate the string!

Hope that helps.




回答2:


[] in [myHighlight]="'yellow'" means that the part in ="..." is an expression. Without '' Angular wants to read the value from an identifier with the name yellow. If you want the literal value, instead of a reference, you need '', the same as you would need in TypeScript.

Without '' Angular interprets the value as string literal, like it is usually done with attribute values in plain HTML+JS.



来源:https://stackoverflow.com/questions/45277131/why-use-apostrophe-for-variables-in-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!