deepthan / blog-angular

Angular 笔记
280 stars 58 forks source link

Angular 如何监听变量变化 #91

Open deepthan opened 4 years ago

deepthan commented 4 years ago

KeyValueChanges 方法

html

<button (click)="a()">1233</button>

ts

import { KeyValueChanges, KeyValueDiffer, KeyValueDiffers } from '@angular/core';

export class Customer {
  firstName: string;
  favoriteColor: string;
}

export  class xx {
   private customerDiffer: KeyValueDiffer<string, any>;
   private customer: Customer;

    constructor(
        private differs: KeyValueDiffers
    ) {
        this.customer = new Customer();
        this.customerDiffer = this.differs.find(this.customer).create();
    }

  customerChanged(changes: KeyValueChanges<string, any>) {
    console.log('changes');
    /* If you want to see details then use
      changes.forEachRemovedItem((record) => ...);
      changes.forEachAddedItem((record) => ...);
      changes.forEachChangedItem((record) => ...);
    */
  }

  ngDoCheck(): void {
      const changes = this.customerDiffer.diff(this.customer);
      if (changes) {
        this.customerChanged(changes);
      }
  }

  a(){
    this.customer.firstName+= "2";
  }

}

使用ngModelChange监听

<input type="text" (ngModelChange)="doSomething($event)" [ngModel]="customer.firstName">

ts

doSomething(event) {
  console.log(event); // logs model value
}

如在动态表单中可使用valueChanges监听

 ngOnInit() {
    this.form = this.fb.group({
     // xxx
    });
  }

  ngAfterViewInit(): void {
    this.form.valueChanges.subscribe((change) => {
      console.log(change)
     })
  }