码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular] Subscribing to the valueChanges Observable

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

标签:ges   bing   add   class   ext   map   ber   product   cal   

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

标签:ges   bing   add   class   ext   map   ber   product   cal   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!