Templates and data binding in Angular

1. Angular Templates

An Angular template is the HTML view that defines how the UI looks. It can include:

  • Standard HTML elements
  • Angular-specific syntax (directives, bindings, pipes)

Example of a simple template:

<h1>Welcome, {{ userName }}!</h1>
<p>{{ message }}</p>
<button (click)="updateMessage()">Click me</button>

Here:

  • {{ userName }} and {{ message }} are interpolation bindings.
  • (click)="updateMessage()" is an event binding.

Template Features

  1. Directives – modify DOM behavior
    • *ngIf → conditional rendering
    • *ngFor → loop through lists
    • ngClass, ngStyle → dynamic styling
<div *ngIf="isLoggedIn">Welcome back!</div>
<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>
  1. Pipes – transform data for display
<p>{{ today | date:'fullDate' }}</p>

2. Data Binding in Angular

Angular provides four types of data binding:

a) Interpolation ({{ }})

  • Binds component data to the template
<p>Hello, {{ userName }}!</p>

b) Property Binding ([ ])

  • Bind DOM properties to component data
<img [src]="imageUrl" alt="My Image">
<button [disabled]="isDisabled">Click</button>

c) Event Binding (( ))

  • Bind DOM events to component methods
<button (click)="onClick()">Click me</button>

d) Two-way Binding ([()])

  • Combine property + event binding
  • Use ngModel to bind input fields
<input [(ngModel)]="userName" placeholder="Enter name">
<p>You entered: {{ userName }}</p>

3. Example Component with Template and Binding

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  userName = 'Alice';
  message = 'Hello Angular!';
  isDisabled = false;
  items = ['Apple', 'Banana', 'Cherry'];

  updateMessage() {
    this.message = 'You clicked the button!';
  }
}
<!-- app.component.html -->
<h1>{{ message }}</h1>
<p>Welcome, {{ userName }}!</p>

<input [(ngModel)]="userName" placeholder="Change name">
<button (click)="updateMessage()" [disabled]="isDisabled">Click me</button>

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

✅ Key Takeaways

  • Templates define UI structure.
  • Data binding connects component data with view.
  • Angular supports interpolation, property, event, and two-way binding.
  • Directives (*ngIf, *ngFor) and pipes enhance templates.

Leave a Reply