Two-Way Data Binding in Angular
Synchronize data between your Angular component and template effortlessly. Learn how to use two-way data binding with ngModel
to create dynamic user interfaces where changes in the view are reflected in the component and vice versa.
Two-way data binding refers to sharing data between a component class and its template. If you change data in one place, it will automatically reflate at the other end. For example, if you change the value of the input box, then it will also update the value of the attached property in a component class.
Two-way data binding performs the following actions:
- Sets a property of a component class
- Listens for a DOM element change event
Angular v2+ supports two-way data binding using ngModel directive and also by having getter and setter methods.
Two-way data binding is a powerful mechanism in Angular that synchronizes data between a component's TypeScript class and its template. This bidirectional connection ensures that changes made in either place are instantly reflected in the other.
Imagine a mirror: any modification to your reflection is immediately replicated on your actual face. Similarly, in two-way data binding, changes in the component's data are reflected in the template, and vice versa.
ngModel Directive
The ngModel
directive with [()]
syntax (also known as banana box syntax) syncs values from
the UI to a property and vice-versa. So, whenever the user changes the value on UI, the corresponding property value
will get automatically updated.
[()]
= [] + ()
where []
binds attribute, and ()
binds an event.
Example: Banana Box [()]
import { Component, OnInit} from '@angular/core';
@Component({
selector: 'app-greet',
template: `
User Name: <input type="text" [(ngModel)]="userName" ><br/>
`
})
export class GreetComponent implements OnInit {
constructor() { }
userName: string = "jbond";
ngOnInit(): void { }
}
The [(ngModel)]
syntax is the recommended way of two-way data binding.
The ngModel
directive with []
syntax is used for one-way data binding.
[ngModel]
binds a value to a property to UI control.
Getter and Setter Methods
For two-way data binding, declare a private property and access its value using get and set methods in the component
class. Then, assign that property to [(ngModel)]
.
For example, declare a private property with a get and set method, as shown below.
Example: Private Property
private _userName: string = "bill gates";
get userName(): string {
return this._userName;
}
set userName(val: string) {
//do some extra work here
this._userName = val;
}
Now, assign userName
to [(ngModel)]
in the template.
Example: [(ngModel)]
<input type="text" [(ngModel)]="userName" >
The following is a full example of two-way data binding using get and set methods.
Example: Two-way Data Binding
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-greet',
template: `
User Name: <input type="text" [(ngModel)]="userName" ><br/>
`
})
export class GreetComponent implements OnInit {
constructor() { }
private _userName: string = "bill gates";
get userName(): string {
return this._userName;
}
set userName(val: string) {
//do some extra work here
this._userName = val;
}
ngOnInit(): void { }
}
While less common, getter and setter methods offer granular control over data synchronization.
TypeScript
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
<input type="text" [(ngModel)]="name">
<p>Hello, !</p>
`
})
export class MyComponent {
private _name = 'World';
get name() {
return this._name;
}
set name(value) {
// Perform additional logic if needed
this._name = value;
}
}
Key Points and Best Practices
- Performance: Be mindful of performance implications when using two-way data binding extensively in complex forms.
- Form Validation: Consider Angular's reactive forms for advanced validation and form handling.
- Clarity: Use clear and descriptive property names.
- Best Practices: Adhere to Angular style guides for consistent code.
Practical Use Cases
Two-way data binding excels in scenarios like:
- User input forms
- Component interactions
- Simple data synchronization
By effectively using two-way data binding, you can create dynamic and responsive Angular applications.