What are the differences between various binding types in Angular?
sobes.tech AI
Answer from AI
In Angular, there are several types of bindings that allow data synchronization between the component and the template. The main types:
-
Property Binding: Passing data from the component to a DOM element. Syntax:
[property]="data". Used to set the value of a DOM element's property.<img [src]="imageUrl"> -
Event Binding: Responding to DOM element events by calling a component method. Syntax:
(event)="method()".<button (click)="onClick()">Click me</button> -
Two-Way Binding: Combines property and event binding, allowing data to be synchronized in both directions between the component and the DOM element. Syntax:
[(ngModel)]="data". Requires importingFormsModule.<input [(ngModel)]="userName"> -
Interpolation: Embedding a string representation of an expression into the template. Syntax:
{{ expression }}. Essentially, syntactic sugar for property binding ([textContent]="expression").<p>Hello, {{ name }}!</p> -
Attribute Binding: Setting the value of an HTML attribute (as opposed to a DOM property). Syntax:
[attr.attribute-name]="data". Often used for attributes that do not have a corresponding DOM property, such asaria-*.<button [attr.aria-label]="buttonLabel"></button> -
Class Binding: Dynamically adding or removing CSS classes. Syntax:
[class.class-name]="condition".<div [class.active]="isActive"></div> -
Style Binding: Dynamically applying CSS styles. Syntax:
[style.style-property]="value"or[style.style-property.unit]="value".<p [style.color]="error ? 'red' : 'black'"></p> <div [style.width.px]="width"></div>
The main differences can be summarized by the data flow direction and the type of bound entities (properties, events, attributes, classes, styles, or text content).