首页 > 其他 > 详细

[Angular] Subscribing to the valueChanges Observable

时间:2017-03-22 20:16:16      阅读:157      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/Answer1215/p/6601715.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!