Angular FAQ: Top Questions
4. What is Two-Way Data Binding?
In Angular, Two-Way Data Binding is a powerful mechanism that enables automatic synchronization of data between the component's class (TypeScript) and its HTML template. This is typically implemented using the [(ngModel)]
directive, which combines both property binding and event binding into a single syntax.
When using two-way binding, any change made to the form element updates the corresponding component property, and any change to the property updates the form element’s value. This ensures a real-time and seamless connection between the view and the underlying data model.
-
Property Binding:
- Sends data from the component class to the DOM (template).
-
Example:
[value]="name"
-
Event Binding:
- Captures events from the DOM and sends them to the component class.
-
Example:
(input)="name = $event.target.value"
-
Two-Way Binding:
-
Combines both property and event binding into one using the
[(ngModel)]
syntax. -
Requires importing the
FormsModule
in your Angular module.
-
Combines both property and event binding into one using the
// app.component.ts
export class AppComponent {
name: string = 'Angular';
}
// app.component.html
<input [(ngModel)]="name">
<p>Hello {{name}}</p>
Explanation of the Example Code:
-
The
<input>
element uses[(ngModel)]="name"
to bind the input value to thename
property in the component class. -
As the user types into the input, Angular updates the
name
property in real-time. -
Any programmatic update to the
name
property is also instantly reflected in the input field and the displayed greeting. -
The
{{name}}
expression ensures the UI reflects the latest value ofname
.
This two-way communication creates a smooth user experience and is especially useful in forms and dynamic UI scenarios.
Note: To use ngModel
, make sure the FormsModule
is imported in your Angular module:
// app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule
]
})
export class AppModule { }