Angularにおけるイベント双方向バインディング

Angularでは、親コンポーネントと子コンポーネントの両方のイベントを双方向でバインディングすることもできます。 子コンポーネントのHTMLテンプレートで、ユーザー名の双方向バインディングと名前を変更する関数を持つ入力フィールドを作成してみましょう:

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

子コンポーネントに移動し、入力処理に必要なデコレータ @Input をインポートします:

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

次に、デコレータ @Input をユーザー名にバインドします。また、デコレータ @Output を onNameChange 関数内で呼び出されるオブジェクト userNameChange にバインドします:

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);
  }
}

次に、メインコンポーネントに移動し、そのクラスに名前プロパティを追加します:

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

親コンポーネントのHTMLテンプレートで、プロパティ userName と親コンポーネントのプロパティ name の値との間で双方向バインディングを実行します:

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

このレッスンの例に従って、親コンポーネントと子コンポーネントのイベント双方向バインディングを実装してください。

Задание 2

前のタスクに基づいて、ユーザーの年齢の双方向バインディングを作成してください。