Sobes.tech
Middle

What are the types of bindings in Angular?

sobes.tech AI

Answer from AI

In Angular, there are several types of bindings that allow synchronizing data between the component and the template:

  • Property Binding: Allows binding an HTML element property to a component property. Changes in the component property value update the HTML property value. Uses square brackets [].

    <img [src]="imageUrl" alt="Image">
    
  • Interpolation: Displays the value of a component property in the template as a string. Uses double curly braces {{}}.

    <p>{{ greeting }}</p>
    
  • Event Binding: Responds to DOM events (e.g., clicks, text input) and calls component methods. Uses parentheses ().

    <button (click)="onClick()">Click me</button>
    
  • Two-Way Binding: Combines property and event binding to synchronize the value between a form element and a component property in both directions. Uses the syntax [(ngModel)]. Requires importing FormsModule.

    <input [(ngModel)]="userName" type="text">
    
  • Attribute Binding: Used for binding HTML attributes that are not DOM properties (e.g., colspan, aria-*). Uses the prefix attr..

    <td [attr.colspan]="colspanCount"></td>
    
  • Class Binding: Allows dynamically adding or removing CSS classes based on a component property.

    <div [class.active]="isActive"></div>
    
  • Style Binding: Sets CSS styles of an element based on a component property.

    <div [style.backgroundColor]="bgColor"></div>