![](/img/trans.png)
[英]How to subscribe to a reactive FormGroup and map the value changes, in angular 6
[英]How can I subscribe to formGroup changes and calculate one of properties from two other?
我有函数创建 formGroup,我需要从其他两个字段中计算一个:sum = price * count。 我怎样才能做到这一点?
public createService = (): FormGroup => {
const group = this.fb.group({
name: [''],
measure: [''],
count: [''],
price: [''],
sum: ['']
});
group.valueChanges.subscribe(res => {
// group.patchValue({...res, sum: +res.price * +res.count});
// res.sum = +res.price * +res.count;
console.log(res);
});
return group;
}
您不必订阅整个表单组。 只需查找价格和计数字段的变化。 像下面这样的东西;
this.group.get('price').valueChanges.subscribe(value => {
this.price = value;
this.calculateSum();
});
this.group.get('count').valueChanges.subscribe(value => {
this.count = value;
this.calculateSum();
});
calculateSum() {
sum = this.price*this.count;
this.group.get('sum').setValue(sum);
}
如果您订阅整个表单并在 value 更改中更新 sum 的值,则会有一个无限的调用周期来更改 value。 相反,您应该订阅单个表单控件。
import { merge } from 'rxjs/observable/merge';
public createService = (): FormGroup => {
const group = this.fb.group({
name: [''],
measure: [''],
count: [''],
price: [''],
sum: ['']
});
merge(
group.get('count').valueChanges,
group.get('price').valueChanges
).subscribe(res => {
this.calculateSum(group);
});
}
calculateSum(group) {
const count = +group.get('count').value;
const price = +group.get('price').value;
group.get('sum').setValue(count + price);
}
import { combineLatest } from 'rxjs';
combineLatest(
this.group.get('count').valueChanges,
this.group.get('price').valueChanges
).subscribe(([count, price]) => {
this.testForm.get('sum').setValue(+count + +price);
});
您可以为字段sum设置属性值,如{{form.count + form.price}}
。 现在我无法测试它,但它是类似的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.