In Angular, property binding is a technique that allows you to bind a component’s template expression to a component’s property. It is similar to interpolation, but it allows you to bind a property of a DOM element to a component property.
Here is an example of property binding in Angular:
import { Component } from '@angular/core';
@Component({
selector: 'app-todo-list',
template: '<input [value]="todoText">'
})
export class TodoListComponent {
todoText = 'Buy milk';
}
In this example, the todoText
property of the TodoListComponent
is bound to the value
property of the input
element using the square brackets ([]
). When the component is rendered, the value of todoText
will be set as the value of the input
element, resulting in the following HTML:
<input value="Buy milk">
Property binding can be used to bind a component’s template to any property of a DOM element, not just the value
property.
Some advantages of using property binding in Angular are:
- It allows you to bind a template expression to a DOM element property, which can be useful for setting the value of an element or modifying its behavior.
- It is easy to use and requires minimal setup.
- It is a one-way data binding technique, meaning that data flows from the component class to the template, but not the other way around. This can help ensure that the component class is the single source of truth for the component’s data.