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)
    The name property is defined in the component, and it’s bound to the input field. Any change to the input will update the name property, and any change to name 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 the name property. The value of the input field will be automatically updated when the name 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.