Two-Way Binding
- Class β HTML + HTML β Class
With two-way binding, changes in the class (TypeScript) are reflected in the HTML, and changes in the HTML are reflected back to the class. Both the class and the view stay in sync.
Example: Two-Way Binding
-
Component (TypeScript)
Thename
property is defined in the component, and itβs bound to the input field. Any change to the input will update thename
property, and any change toname
will update the input.export class TwoWayComponent implements OnInit { public name = "Shoyeb"; // Property constructor() {} ngOnInit(): void {} }
-
HTML
The[(ngModel)]
directive binds the input field to thename
property. The value of the input field will be automatically updated when thename
changes, and vice versa.<input [(ngModel)]="name" type="text"> <h2>{{ name }}</h2>
Important: Add FormsModule
to app.module.ts
To enable two-way binding, you need to import FormsModule
into the app.module.ts
.
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
// components
],
imports: [
// other modules
FormsModule // Add this line
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
Key Concepts:
-
[(ngModel)]
: This syntax is called banana in a box because of the[( )]
brackets and parentheses, which represent both property binding and event binding in one. -
Two-Way Binding: The value of the input field and the property in the component (
name
) are bound together. Changes in one will reflect in the other automatically.