首页 > 代码库 > [Angular] Subscribing to the valueChanges Observable

[Angular] Subscribing to the valueChanges Observable

For example we have built a form:

  form = this.fb.group({    store: this.fb.group({      branch: ‘‘,      code: ‘‘    }),    selector: this.createStock({}),    stock: this.fb.array([])  });

 

We want to reponse to each time ‘stock‘ value changes. 

To do that we can subscrube ‘valueChanges‘ for form.

Notice that, ‘valueChanges‘ is an Observable, you need to subscribe to it, And it not only exists for ‘form‘, also for ‘formControl, formGroup, formArray‘:

this.form.get(stock)    .valueChanges    .subscribe(...)

 

If you want to give an initial value, you can use ‘startWith‘ from ‘rxjs/add/opreator/startWith‘.

      this.form.get(stock)        .valueChanges        .startWith(this.form.get(stock).value)        .subscribe((stocks) => {          this.total = this.calculateTotal(stocks);        })  calculateTotal(stocks: Item[]): number {    return stocks.reduce((acc, next) => {      return acc + (Number(next.quantity) * Number(this.productMap.get(next.product_id).price))    }, 0)  }

 

[Angular] Subscribing to the valueChanges Observable