For example i can use {{}} bindings:
<h1>{{title}}</h1>
or [] property bindings:
<img [src]="imgsrc">
So what’s the differences between the two?
CodePudding user response:
with string interpolation '{{}}' you can bind expressions that only can be converted into a strings. But if you want to bind other type you can use property binding '[]' example:
you hava a variable that contains a boolean value:
isLoading = false;
so, if you use string interpolation, you actually convert false to 'false'
<p>{{isLoading}}</p>
That convert the value of isLoading to a string 'false' to rederize on the DOM.
But if you bind with property binding you will be pass the boolean value, and not will be converted to string
<button [disabled]="isLoading"></button>
CodePudding user response:
The difference between [ ]
and {{ }}
can be summarised in that one is used for property binding and the other as a means for string interpolation.
To quote for the [ ]
:
To bind to an element's property, enclose it in square brackets,
[ ]
, which identifies the property as a target property.
This the use case for [ ]
is for property binding, when we want to set the value of attribute of an HTML element. This is most commonly used for binding of HTML attributes, like the [src]
attribute in the img
tag. The other use case is to pass values from a parent component to a child component.
The full explanation of this mechanism can be found in the official documentation.
For example, consider the following HTML:
<button [disabled]="true">Foo</button>
Here the button is disabled since we are setting the HTML attribute disabled
to true
.
Regarding the {{ }}
:
Interpolation refers to embedding expressions into marked up text. By default, interpolation uses the double curly braces
{{
and}}
as delimiters.
This is used when we want to display a value in our HTML that is given by the value of a variable from our typescript. It simply replaces the value of the typescript variable in the HTML. The full explanation of this can be found in the official documentation.
For example, consider the following TS and HTML:
<button>{{ foo }}</button>
@Component(...)
export class CustomComponent {
foo = 'Click me!';
}
Angular would render a button with the text 'Click me!'
after change detection had run:
<button>Click me!</button>
If we where to change the value of the foo
variable, it would also update the value displayed in the button.