Loading...

Two-Way Data Binding in Angular

Two-way data binding in Angular allows data to flow in both directions:

  • From the component to the view (displaying data).
  • From the view to the component (updating data).

Syntax

The syntax for two-way data binding uses the ngModel directive inside [( )] brackets:

<input [(ngModel)]="propertyName">

Example

Steps to use ngModel directive in angular app.

1. Import FormsModule

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

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms'; // Import FormsModule

@NgModule({
	declarations: [AppComponent],
  imports: [BrowserModule, FormsModule], // Add FormsModule here
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
2. Component (TypeScript) - app.component.ts
import { Component } from '@angular/core';
			@Component({
				selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
				})
export class AppComponent {
  userName: string = 'John Doe';
}

3. Template (HTML) - app.component.html

<h2>Two-Way Data Binding Example</h2>

<!-- Input field with two-way data binding -->
<input type="text" [(ngModel)]="userName">

<!-- Display the updated value -->
<p>Hello, {{ userName }}!</p>

How It Works

  • When the user types in the input field, the userName property in the component updates automatically.
  • The view (HTML) also updates immediately when the property changes.
  • This is two-way data binding, as both the view and the component are in sync.

Advantages of Two-Way Data Binding

Advantage Description
Automatic UI updates The UI reflects changes in the component immediately.
Less boilerplate code Eliminates the need to manually update UI elements.
Better user experience Users see changes in real-time as they interact with the UI.

Conclusion

Two-way data binding in Angular helps keep the UI and component in sync with minimal effort. By using [(ngModel)], data flows seamlessly between the view and the component.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!