问题
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