Why use apostrophe for variables in Angular 4
Asked Answered
G

2

0

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.

Guillaume answered 24/7, 2017 at 9:38 Comment(0)
S
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.

Stu answered 24/7, 2017 at 9:43 Comment(0)
P
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.

Pic answered 24/7, 2017 at 9:43 Comment(0)
S
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.

Stu answered 24/7, 2017 at 9:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.