Two-way Event Binding in Angular

Also in Angular you can make a two-way binding of events of both components: parent and child. Let's make an input in the child HTML template with a two-way binding of the user name and the function that changes the name:

app/user/user.component.html<input [ngModel]="userName" (ngModelChange)="onNameChange($event)" />

Let's go to our child component and import the @Input decorator into it. It is needed to work with inputs:

app/user/user.component.tsimport { Component, Input, Output, EventEmitter } from '@angular/core';

Next, we bind the @Input decorator to the username. And we bind the @Output decorator to the userNameChange object, which will be called in the onNameChange function:

app/user/user.component.tsexport class UserComponent {
  @Input() userName: string = '';
  @Output() userNameChange = new EventEmitter<string>();
  onNameChange(model: string) {
    this.userName = model;
    this.userNameChange.emit(model);
  }
}

Now we go to the main component and add the name property to its class:

app/app.component.tsexport class AppComponent {
  name: string = 'alex';
}

And in the HTML template of the parent component, we perform a two-way binding of the userName property with the value of the name property of the parent component:

ap.component.html<user-data [(userName)]="name"></user-data>
<p>You choose name: {{ name }}</p>
Задание 1

Implement two-way binding of events between parent and child components according to the example given in the lesson.

Задание 2

Based on the previous task, make a two-way binding of the user's age.