我希望total
框的值等于price
和quantity
的乘积。没有反应式,通过在框内使用香蕉语法非常容易。如何在反应形式中实现相同的目标
这是我的表单代码
addProductFormGroup(): FormGroup {
return this._formBuilder.group({
productId: ['', Validators.required],
price: ['', Validators.required],
loanTermId: ['', Validators.required],
quantity: ['', Validators.required],
deposit: ['', Validators.required],
total: ['', Validators.required],
});
}
这是total
输入的html
<mat-form-field appearance="outline" fxFlex="100" class="pr-4">
<mat-label>Total </mat-label>
<input type='number' value='deposit*quantity' formControlName="total" [id]="'total' + i" matInput name="" id="" placeholder="Total" required>
</mat-form-field>
答案 0 :(得分:2)
value='33' // dont do that
addProductFormGroup(): FormGroup {
return this._formBuilder.group({
productId: ['', Validators.required],
price: ['', Validators.required],
loanTermId: ['', Validators.required],
quantity: ['', Validators.required],
deposit: ['', Validators.required],
total: ['33', Validators.required], // do that!
});
}
编辑:
根据您的回应,我想说total
从formGroup中删除,因为它实际上不是用户输入。宁可做些喜欢的事情:
total$: Observable<number>;
this.total$ = this.productFormGroup.valueChanges.pipe(
map(formValue => +formValue.quantity * +formValue.price)
)
<div>Total: {{ total$ | async }}</div>
答案 1 :(得分:1)
让我知道是否可以解决(Link to StackBlitz)
ngOnInit(){
this.formGroup = this.fb.group({
quantity : [0 ,[]],
value:[0,[]],
total:[0]
})
this.formGroup.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(this.isSame)
).subscribe(values =>{
console.log(values)
const {value, quantity} = values;
this.formGroup.patchValue(
{
total : value * quantity
}
)
})}
isSame(prev, next) {
return (prev.value === next.value)
&& (prev.quantity === next.quantity);
}
https://stackblitz.com/edit/angular-8t3qpo?embed=1&file=src/app/app.component.ts
答案 2 :(得分:0)
我认为您只需要做
public get total(): any {
if (this.form.get('price').value && this.form.get('quantity').value) {
return this.form.get('price').value * this.form.get('quantity').value;
}
return '';
}
注意::您需要创建表单,并需要在其中存储formGroup返回值
答案 3 :(得分:0)
您可以订阅类似于以下内容的价值变更:
// build formgroup then ...
// calculate total
this.formGroup.valueChanges
.pipe(debounceTime(20), takeUntil(this.destroyed$))
.subscribe(value => {
this.calculateLineItemTotal();
});
private calculateLineItemTotal(): number {
// get quantity and rate values
const quantity = +this.formGroup.controls.LineQuantity.value;
const rate = +this.formGroup.controls.LineRate.value;
// verify if blank
if (!quantity || !rate) {
this.formGroup.controls.LineTotal.setValue("", {
emitEvent: false
});
return 0;
}
this.formGroup.controls.LineTotal.setValue((quantity * rate).toFixed(2), {
emitEvent: false
});
return quantity * rate;
}
警告-这种方法很快会出现丑陋的情况(在编辑模式下请考虑修补值),因此最好避免在注释中暗示为詹森。