首页 > 代码库 > [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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。