Angular 4: How to watch an object for changes?

后端 未结 6 802
死守一世寂寞
死守一世寂寞 2021-01-30 20:45

ETA: I know that there are various ways to watch my form for changes. That is not what I am trying to do. As the title says, I am asking how to watch for change

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 21:22

    Angular usually uses injected into constructor KeyValueDiffers class.

    For your case it could look like:

    import { KeyValueChanges, KeyValueDiffer, KeyValueDiffers } from '@angular/core';
    
    export class Customer {
      firstName: string;
      favoriteColor: string;
    }
    
    @Component({
      selector: 'my-app',
      templateUrl: `./app.component.html`
    })
    export class AppComponent {
      private customerDiffer: KeyValueDiffer;
      private customer: Customer;
    
      constructor(private differs: KeyValueDiffers) {}
    
      ngOnInit(): void {
        this.customer = new Customer();
        this.customerDiffer = this.differs.find(this.customer).create();
      }
    
      customerChanged(changes: KeyValueChanges) {
        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);
          }
      }
    }
    

    Stackblitz Example

    One more option is using setter on properties that you want to check.

    See also

    • http://blog.mgechev.com/2017/11/14/angular-iterablediffer-keyvaluediffer-custom-differ-track-by-fn-performance/

提交回复
热议问题