Menu

Data Binding and Directives

Data Binding and Directives

Interpolation and Property Binding

Interpolation ({{ }}) displays a component variable's value directly in the template, while Property Binding ([property]="value") dynamically updates an HTML element's property using data from the component.

<!-- Interpolation -->

<h1>Welcome to {{ courseName }}!</h1>

<!-- Property Binding -->

<img [src]="imageUrl" [alt]="imageAlt">

<button [disabled]="isLoading">Submit</button>

Event and Two-Way Binding

Event Binding ((event)="handler()") responds to user actions such as button clicks or keyboard input. Two-Way Binding ([(ngModel)]) synchronizes the component data and the user interface automatically.

<!-- Event Binding -->

<button (click)="enrollNow()">Enroll Now</button>

<!-- Two-Way Binding -->

<input [(ngModel)]="userName" placeholder="Your name">

<p>Hello, {{ userName }}!</p>

Note: To use ngModel, import FormsModule in app.module.ts.

Structural and Attribute Directives

Structural directives modify the DOM by adding or removing elements.

<ul>

<li *ngFor="let course of courses">{{ course }}</li>

</ul>

<p *ngIf="isLoggedIn">Welcome back!</p>

Attribute directives modify the appearance or behavior of existing elements.

<span [ngClass]="{ 'active': isActive, 'disabled': !isActive }">

Status

</span>

<p [ngStyle]="{ 'color': isActive ? 'green' : 'gray' }">

Status

</p>