Two-way Binding

In Object Oriented languages where we have concept of objects, we shouldn’t really pass parameters around. Because an object encapsulates some data, and some behavior.

A component encapsulates the data, the logic, and the HTML markup behind the view.

Fill the form by default and display the new value on the console by hit enter:

#1 Property binding method

@Component({
  selector: 'app-root',
  template: `
    <input 
      [value]="email" keyup.enter)="email = $event.target.value; onKeyUp()">`,
})
export class AppComponent {
  email = "gabor@gmail.com";

  onKeyUp(){
    console.log(this.email);
  }
}

#2 method Two-Way binding with ngModel

“Banana Box” syntax

Don’t forget to import formsModule in module.ts

@Component({
  selector: 'app-root',
  template: `
      <input [(ngModel)]="email" (keyup.enter)="onKeyUp()" />
    `
})
export class AppComponent {
  email = "gabor@gmail.com";
  
  onKeyUp(){
    console.log(this.email);
  }
}
Was this page helpful?