Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular 如何监听变量变化 #91

Open
deepthan opened this issue Sep 10, 2020 · 0 comments
Open

Angular 如何监听变量变化 #91

deepthan opened this issue Sep 10, 2020 · 0 comments
Labels

Comments

@deepthan
Copy link
Owner

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)
     })
  }
@deepthan deepthan added the event label Sep 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant