Property binding in angular means associating the property of an element with a property of 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.

0
Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.