[英]How can I subscribe to formGroup changes and calculate one of properties from two other?
I have function creates formGroup and I need to calculate one of field from two others: sum = price * count.我有函数创建 formGroup,我需要从其他两个字段中计算一个:sum = price * count。 How can I do that?
我怎样才能做到这一点?
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;
}
You don't have to subscribe the whole form group.您不必订阅整个表单组。 Just look for changes on price and count fields.
只需查找价格和计数字段的变化。 Something like below;
像下面这样的东西;
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);
}
If you subscribe to the whole form and update the value of sum inside value changes there will be an infinite call cycle to value changes.如果您订阅整个表单并在 value 更改中更新 sum 的值,则会有一个无限的调用周期来更改 value。 Instead you should subscribe to individual form controls.
相反,您应该订阅单个表单控件。
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);
});
You can set the attribute value for the field sum like {{form.count + form.price}}
.您可以为字段sum设置属性值,如
{{form.count + form.price}}
。 Now I can't test it, but it's something like that.现在我无法测试它,但它是类似的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.