π Data Binding & Directives
Interpolation, property/event binding, structural (*ngIf, *ngFor), attribute directives, and control flow syntax.
The Four Types of Data Binding
Data binding coordinates communication between the component TypeScript class and the HTML view template.
| Binding Type | Syntax | Direction | Description |
|---|---|---|---|
| Interpolation | {{ expression }} | Component β View | Embeds dynamic string values in template. |
| Property Binding | [property]="value" | Component β View | Sets DOM properties dynamically. |
| Event Binding | (event)="handler()" | View β Component | Listens for user events like clicks & keypresses. |
| Two-Way Binding | [(ngModel)]="property" | Component β View | Keeps model and input view synchronized. |
Data Binding Examples
Combining property, event, and two-way data bindings in Angular forms.
binding.component.ts
TypeScript
import { Component } from '@angular/core'; @Component({ selector: 'app-binding', template: ` <h2>{{ title }}</h2> <img [src]="imageUrl" [alt]="title" /> <input [(ngModel)]="username" placeholder="Enter name" /> <button (click)="resetName()" [disabled]="!username">Reset</button> ` }) export class BindingComponent { title = 'Data Binding Demo'; imageUrl = 'assets/logo.png'; username = ''; resetName() { this.username = ''; } }
Built-in Structural Directives (*ngIf, *ngFor, *ngSwitch)
Structural directives alter DOM layout by adding, removing, or manipulating elements.
directives.component.html
HTML
<!-- Conditional rendering -->
<div *ngIf="isLoggedIn; else loginTemplate">
Welcome back, User!
</div>
<ng-template #loginTemplate>
<p>Please log in.</p>
</ng-template>
<!-- List iteration -->
<ul>
<li *ngFor="let item of items; let i = index; trackBy: trackById">
{{ i + 1 }}. {{ item.name }}
</li>
</ul>
Modern Control Flow Syntax (Angular 17+)
Angular 17 introduced built-in `@if`, `@for`, and `@switch` control flow blocks, offering cleaner syntax and improved performance without requiring directive imports.
control-flow.component.html
HTML
@if (isLoggedIn) {
<p>Welcome Back!</p>
} @else {
<p>Please Log In</p>
}
@for (item of items; track item.id) {
<div class="item-card">{{ item.name }}</div>
} @empty {
<p>No items found.</p>
}
Tip: Built-in `@for` requires explicit `track` expression, preventing common performance pitfalls with list re-rendering.