In Angular, we have multiple ways of binding properties of components to the DOM elements. Such as:
One Way Data Binding techniques in Angular
1. String Interpolation - This is double curly bracket syntax we use to display the data.
<h2>{{ title }}</h2>
<img src="{{ imageUrl }}" />
Now, this String Interpolation is just a syntactical sugar. Behind the scene, when angular compiles the view, it converts this interpolation into what we call property binding. Just as below:
<h2 [textContent]="title"></h2>
<img [src]="imageUrl" />
2. Property Binding - With property binding, we bind a property of DOM object (i.e. src
here) with a property of the component (i.e. imageUrl
).
<h2 [textContent]="title"></h2>
<img [src]="imageUrl" />
The syntax is to use the DOM object property in a square bracket.
Note, above we used textContent
to bind the content of the h2
tag. because textContent
is the property of the h2
DOM object.
3. Attribute Binding - We might have HTML attributes in an element that don't have a property in the DOM object. Here colspan
is an example. DOM object oftd
element doesn't have any property with name colspan
. So, below binding won't work.
<td [colspan]="colspan"></td>
Solution is to use attr
prefix before attribute.
<td [attr.colspan]="colspan"></td>
4. Class Binding - There might be the time when you want to bind the class based on the state of underlying component. For this, we use class binding. Class binding is a variation of property binding.
<button class="btn btn-primary" [class.active]="isActive">Save</button>
In above example, active
class will be applied only when isActive
field value is true.
5. Style Binding - Style Binding is also a variation of property binding similar to the class binding. Style Binding is used when we want to apply some inline style based on some condition.
<button [style.backgroundColor]="isActive ? 'green' : 'blue'">Save</button>
Above example will update the background color of the button on the basis of isActive
field.
Note, here we can use only those properties which are part of the DOM style object. Here backgroundColor
is a valid style object property. Here you can find a complete list of DOM Style object properties. HTML DOM Style Object Properties
6. Event Binding - In angular, we also event binding which we use to handle events raised from the DOM elements. Such as click, keyup, mouseover etc.
<button (click)="onSave($event)">Save</button>
This $event
object is something known to angular. This $event
object represent an standard DOM event.