How to bind data in Angular
Angular data binding connects component data with template elements, enabling dynamic user interfaces that automatically update when data changes. This creates reactive applications with seamless data flow between components and templates.
Use Angular’s four binding types: interpolation {{}}
, property binding []
, event binding ()
, and two-way binding [()]
.
// component.ts
import { Component } from '@angular/core'
@Component({
selector: 'app-demo',
templateUrl: './demo.component.html'
})
export class DemoComponent {
title = 'Angular Data Binding'
isVisible = true
count = 0
userInput = ''
user = {
name: 'John Doe',
email: '[email protected]'
}
handleClick() {
this.count++
}
onInputChange(event: Event) {
const target = event.target as HTMLInputElement
this.userInput = target.value
}
}
<!-- demo.component.html -->
<!-- Interpolation: Display data -->
<h1>{{ title }}</h1>
<p>Welcome {{ user.name }}!</p>
<p>Count: {{ count }}</p>
<!-- Property Binding: Set element properties -->
<button [disabled]="count >= 10">Click Me</button>
<img [src]="user.avatar" [alt]="user.name">
<div [class.active]="isVisible" [style.color]="count > 5 ? 'red' : 'blue'">
Dynamic Styling
</div>
<!-- Event Binding: Handle user interactions -->
<button (click)="handleClick()">Increment ({{ count }})</button>
<input (input)="onInputChange($event)" placeholder="Type here">
<!-- Two-way Binding: Form inputs -->
<input [(ngModel)]="userInput" type="text">
<p>You typed: {{ userInput }}</p>
<select [(ngModel)]="user.name">
<option value="John Doe">John</option>
<option value="Jane Smith">Jane</option>
</select>
Angular provides four data binding types: interpolation displays component data in templates, property binding sets element properties dynamically, event binding handles user interactions, and two-way binding combines property and event binding for form inputs. Use interpolation for text display, property binding for attributes and styles, event binding for user actions, and two-way binding with ngModel for form controls.
Best Practice Note:
This is the same data binding approach used in CoreUI Angular components. Use appropriate binding types for each scenario, avoid complex expressions in templates, handle events properly for user interactions, and leverage Angular’s change detection for automatic view updates.