Square brackets imply binding, whereas omitting them does an attribute assignment (there's more to it, which I'll cover later). If you're doing a binding, the value in quotes has to be a JavaScript expression.
This line:
<mat-tab-group backgroundColor="primary">
simply assigns the value "primary" to the attribute backgroundColor
. If the value "primary" doesn't exist, it depends on the component what to do with it.
This line:
<mat-tab-group [backgroundColor]="primary">
is a binding to a field named primary
. It implies that in order to assign the attribute value, Angular will look for a field named primary
, read its value and assign that instead. If the field named primary
does not exist, it will assign a value of undefined
. For example, if you have this:
primary = 'red';
then the second statement (with binding) will actually assign the value of "red" to your attribute, whereas the first statement (no binding) will still assign a value of "primary".
There are three additional things to note:
- You can also do a binding by omitting the square brackets and using double braces instead, e.g.
<mat-tab-group backgroundColor="{{primary}}">
. The two are exactly equivalent, but the square bracket style is more familiar to everyone and you should always use it unless you have a good reason.
- Because the binding accepts a JavaScript expression, you can supply more than a simple field, e.g.
<mat-tab-group [backgroundColor]="primary || secondary">
, will assign the value from the secondary
field if primary
is undefined. Also, <mat-tab-group [backgroundColor]="shade + 'blue'">
will evaluate the field shade
and add the value "blue" to it, yielding "lightblue" or "darkblue" depending on the value of shade
.
- If the property you're assigning to is boolean, then it becomes really easy to mess it up.
<my-comp active="true">
assigns a the text "true" to the active
property, whereas <my-comp [active]="true">
assigns the boolean value true
. This may be an important distinction in your code, or may not. And since the two look so similar, I have personally missed that mistake for months. There are probably still a few lurking around somewhere.