What is Data Binding in Angular: Simple Explanation and Example
data binding is a way to connect the user interface (UI) with the component's data so they stay in sync automatically. It allows changes in the UI to update the data and changes in the data to update the UI without extra code.How It Works
Think of data binding in Angular like a two-way conversation between your app's data and what the user sees on the screen. When the data changes, the UI updates itself, and when the user interacts with the UI, the data changes too. This keeps everything in sync without you having to manually update both sides.
Angular uses special syntax to set up this connection. For example, you can display data inside HTML using double curly braces, or bind input fields so that typing updates the data instantly. This is like having a smart assistant who listens and updates both your notes and your display at the same time.
Example
This example shows a simple input box bound to a variable. When you type in the box, the text below updates automatically.
import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-data-binding', template: ` <h2>Data Binding Example</h2> <input [(ngModel)]="name" placeholder="Enter your name" /> <p>Hello, {{ name }}!</p> ` }) export class DataBindingComponent { name = ''; }
When to Use
Use data binding whenever you want your app's data and UI to stay in sync without extra work. It's perfect for forms, live updates, and interactive features where user input changes the data or the data changes what the user sees.
For example, in a shopping cart app, data binding can update the total price instantly when the user changes quantities. Or in a chat app, it can show new messages as they arrive without refreshing the page.
Key Points
- Data binding connects UI and data automatically.
- Angular supports one-way and two-way binding.
- Two-way binding uses
[(ngModel)]syntax. - It reduces manual DOM updates and keeps code clean.