Angular 4: How to watch an object for changes?

后端 未结 6 799
死守一世寂寞
死守一世寂寞 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:41

    You could use custom setters to trigger your callback:

    class Customer {
      private _firstName: string
      get firstName(): string {
        return this._firstName
      }
      set firstName(firstName: string) {
        this.valueChanged(this._firstName, firstName)
        this._firstName = firstName
      }
    
      private _lastName: string
      get lastName(): string {
        return this._lastName
      }
      set lastName(lastName: string) {
        this.valueChanged(this._lastName, lastName)
        this._lastName = lastName
      }
    
      valueChanged: (oldVal, newVal) => void
    
      constructor (valueChanged?: (oldVal, newVal) => void) {
        // return an empty function if no callback was provided in case you don't need
        // one or want to assign it later
        this.valueChanged = valueChanged || (() => {})
      }
    }
    

    Then just assign the callback when you create the object:

    this.customer = new Customer((oldVal, newVal) => console.log(oldVal, newVal))
    
    // or
    
    this.customer = new Customer()
    this.customer.valueChanged = (oldVal, newVal) => console.log(oldVal, newVal)
    

提交回复
热议问题