Property Binding
Property binding in angular means associating the property of an element with a property of angular component class.
Property binding is essentially an assignment statement where element property is assigned the value of a component property.
The property of HTML element is written at the left hand side enclosed between square brackets([ and ]) and component property is written at the right.
Property binding makes an angular component dynamic in that you can control the behavior of elements with properties at run time.
Syntax
Angular property binding syntax is given below.
<img [src] = “url” ></img>
where src
is the property of the img
element which is assigned the value of component property url
. Corresponding component class will be as below.
export class PropertyBinder { // url property public String url = "https://randomimage.com/id=2323"; }
With above property binding syntax, the img
element will be rendered in the browser as
<img src = “https://randomimage.com/id=2323”></img>
Interpolation Vs Property binding
In the last section, you learnt about interpolation which allows to use a component property in the corresponding template.
Interpolation can also be used to bind component properties to the properties of HTML template elements.
Thus, using interpolation, img
element can be written as
<img src = “{{ url }}” ></img>
Notice that src
property is not enclosed between square brackets as with property binding. It works the same way as the example given above.
Now the question arises, when should you use property binding and when to use interpolation?
The answer is, interpolation should be used to display the value of a component property as a text such as that in a heading, div, paragraph or a span as below.
<h1>{{ url }}</h1>
For using property binding in the above element with interpolation syntax, it needs to be modified as
<h1 [textContent] = “url” ></h1>
which is obviously not better as compared to interpolation syntax.
Property binding in angular can be used in various scenarios such as
1. Binding property to attributes
Attributes of HTML elements can be assigned values directly from properties as shown in below example
<h2 [title]="pageTitle">Learning angular!</h2>
Here, title
attribute of h2 tag is supplied from value of property pageTitle
.
2. Conditional rendering
Property binding can also be used with directives such as ngIf
for rendering elements conditionally as in below example.
<div *ngIf="isUserLoggedIn">You are logged in!</div>
Here, the div
will be rendered based on the value of isUserLoggedIn
property.
3. Binding to style
Element style can also be assigned directly through class properties using property binding as in this example.
<button [style.backgroundColor]="buttonColor">Click Me</button>
In above code, backgroundColor
style of button is assigned through property buttonColor
.