การผูกเหตุการณ์สองทางใน Angular

ใน Angular ยังสามารถทำการผูกเหตุการณ์สองทาง ของคอมโพเนนต์ทั้งสองได้: คอมโพเนนต์หลักและคอมโพเนนต์ย่อย ลองทำ ในเทมเพลต HTML ของคอมโพเนนต์ย่อยเป็นอินพุตที่มีการผูกสองทาง ของชื่อผู้ใช้และฟังก์ชัน ที่เปลี่ยนชื่อ:

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

ไปที่คอมโพเนนต์ย่อยของเราและ นำเข้า Decorator @Input ลงไป มันจำเป็นสำหรับการทำงานกับอินพุต:

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

ต่อไปผูก Decorator @Input กับชื่อผู้ใช้ และผูก Decorator @Output กับออบเจ็กต์ userNameChange, ซึ่งจะถูกเรียกในฟังก์ชัน onNameChange:

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>คุณเลือกชื่อ: {{ name }}</p>
Задание 1

นำการผูกเหตุการณ์สองทาง ของคอมโพเนนต์หลักและคอมโพเนนต์ย่อยไปใช้ ตามตัวอย่างที่ให้ไว้ในบทเรียน

Задание 2

จากโจทย์ก่อนหน้า ให้ทำ การผูกสองทางของอายุผู้ใช้