如何订阅formGroup更改并从另两个属性中计算一个属性



我有一个函数创建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;
}

如果订阅整个表单并在值更改中更新sum的值,则将有一个对值更改的无限调用周期。相反,您应该订阅各个表单控件。

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);
}

您不必订阅整个表单组。只需查找价格和计数字段的变化。下面这样的东西;

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);
}
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}}。现在我不能测试它,但它是这样的。

最新更新