ค้นหาเว็บไซต์

TypeScript - การตรวจจับการเปลี่ยนแปลงใน Angular 2.0


ฉันมีคอมโพเนนต์ Angular2.0:

import {Component, View, FORM_DIRECTIVES} from 'angular2/angular2';

@Component({
  selector: 'font-size-component',
  properties: ['fontSize'],
  events: ['fontSizeChanged']
})
@View({
  template: `<input id="fontSize" [(ng-model)]="fontSize"/>`,
  directives: [FORM_DIRECTIVES]
})
export class FontSizeComponent {
  constructor() {

  }
}

ตอนนี้ ฉันต้องการให้คอมโพเนนต์นี้ทำให้เกิดอีเวนต์ (โดยใช้การผูกอีเวนต์) เมื่อค่าของอินพุตเปลี่ยนแปลง

ใน Angular 1.X ผมมีตัวเลือกหลายอย่าง (ng-change หรือ $scope.$watch) ผมกำลังมองหาวิธีแก้ปัญหาที่คล้ายกัน ดังนั้นเมื่ออินพุตเปลี่ยน ผมจะสามารถใช้ eventemitter และทริกเกอร์เหตุการณ์ fontSizeChanged ได้

ขอบคุณ,

ยา นีฟ

คำตอบ #1

  1. คุณสามารถใช้ getter และ setter ของ JavaScript ดังนั้นคอมโพเนนต์ของคุณจะมีลักษณะดังนี้:
import {Component, View, FORM_DIRECTIVES, EventEmitter} from 'angular2/angular2';

@Component({
    selector: 'font-size-component',
    properties: ['fontSize'],
    events:     ['fontSizeChange']
})
@View({
    template: `
        <input id="fontSize" [(ng-model)]="fontSizeModel"/>
    `,
    directives: [FORM_DIRECTIVES]
})
export class FontSizeComponent {
    fontSize: string;
    fontSizeChange = new EventEmitter();

    get fontSizeModel() {
        return this.fontSize;
    }

    set fontSizeModel(value) {
        this.fontSizeChange.next(value);
    }
}

ลองดู plnkr อันนี้

  1. วิธีแก้ปัญหาที่แตกต่างเล็กน้อยคือการใช้การผูกเหตุการณ์ (input):
@Component({
    selector: 'font-size-component',
    properties: ['fontSize'],
    events:     ['fontSizeChange']
})
@View({
    template: `
        <input 
          id="fontSize" 
          [value]="fontSize" 
          (input)="fontSizeChange.next($event.target.value)"
        />
    `,
    directives: [FORM_DIRECTIVES]
})
export class FontSizeComponent {
    fontSize: string;
    fontSizeChange = new EventEmitter();
}

ดู plnkr นี้

คำตอบ #2

คุณยังสามารถเข้าถึง lifecycle hooks ของ Angular2 ได้ จากเอกสาร:

ngOnChanges(changeRecord) { ... }
ถูกเรียกหลังจากมีการเปลี่ยนแปลงทุกครั้งของคุณสมบัติ input และก่อนการประมวลผลเนื้อหาหรือมุมมองลูก

ดูที่ https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

เพียงเพิ่มวิธีการนี้ลงในคลาสคอมโพเนนต์ของคุณ:

ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
  if (changes['fontSize']) { // fire your event }
}

คำแนะนำด้านบนรวมถึง Plunkr สำหรับสิ่งนี้: https://angular.io/resources/live-examples/lifecycle-hooks/ts/plnkr.html

บทความที่เกี่ยวข้อง