Angular Data Binding

Angular Data Binding

Angular provides four types of data binding to connect your component class to the template.

1 — Interpolation {{ }}

<h1>{{ title }}</h1>
<p>{{ user.name.toUpperCase() }}</p>
<p>Total: {{ price * quantity | currency }}</p>

2 — Property Binding [ ]

<!-- Bind a component/DOM property to a class expression -->
<img [src]="imageUrl" [alt]="imageAlt" />
<button [disabled]="isLoading">Submit</button>
<app-card [title]="cardTitle" [user]="currentUser" />

<!-- Class and style binding -->
<div [class.active]="isActive"></div>
<div [class]="{ active: isActive, error: hasError }"></div>
<p [style.color]="textColor"></p>
<p [style]="{ fontSize: size + 'px', fontWeight: 'bold' }"></p>

3 — Event Binding ( )

<button (click)="handleClick()">Click Me</button>
<input (keyup.enter)="search()">
<form (ngSubmit)="onSubmit()">...</form>

<!-- Access the event object -->
<button (click)="handleClick($event)">Click</button>

4 — Two-Way Binding [( )]

<!-- Requires FormsModule -->
<input [(ngModel)]="username" />
<p>Hello, {{ username }}</p>
// app.component.ts
username = 'Alice';
// As user types, username updates; as username changes, input updates