我正在尝试使用角度6反应形式从定价中计算折扣百分比或折扣金额。
form.component.html (简体)
...
<form [formGroup]="productForm">
<mat-form-field class="quat-width">
<span matPrefix>$ </span>
<input matInput type="number" name="CostPrice" formControlName="CostPrice">
</mat-form-field>
<mat-form-field class="quat-width">
<span matPrefix>$ </span>
<input matInput type="number" name="ListPrice" formControlName="ListPrice">
</mat-form-field>
<mat-form-field class="quat-width">
<span matPrefix>$ </span>
<input matInput type="number" name="DiscountAmount" formControlName="DiscountAmount">
</mat-form-field>
<mat-form-field class="quat-width">
<span matPrefix>% </span>
<input matInput type="number" name="DiscountPercent" formControlName="DiscountPercent">
</mat-form-field>
</form>
form.component.ts (简体)
...
export class ProductFormComponent implements OnInit {
productForm: FormGroup;
constructor(
private fb: FormBuilder,
private productService: ProductsService) { }
ngOnInit() {
this.createForm();
}
createForm() {
this.productForm = this.fb.group({
DiscountAmount: [0],
DiscountPercent: [0],
DiscountPrice: [0],
ListPrice: [0],
});
this.productForm.valueChanges.debounce(250).subscribe(val =>{
if (val.ListPrice > 0 && val.DiscountAmount > 0) {
const newVal = Math.round((val.ListPrice / val.DiscountAmount) * 100);
this.productForm.controls.DiscountPercent.patchValue(newVal);
}
if (val.ListPrice > 0 && val.DiscountAmount > 0) {
const newVal = Math.round((discPercent / 100) * val.ListPrice);
this.productForm.controls.DiscountAmount.patchValue(newVal);
}
}
this.validateForm();
}
validateForm() {
Object.keys(this.productForm.controls).forEach(key => {
this.productForm.controls[key].markAsTouched();
this.productForm.controls[key].updateValueAndValidity();
});
}
}
上面的代码是我到目前为止所无法实现的,创建了一个最大的调用堆栈到达错误。
如果更改标价和折扣百分比时如何设置折扣金额的值,如何在更改标价和折扣金额时如何设置折扣百分比的值?
答案 0 :(得分:0)
您可以对patchValue和updateValueAndValidity使用{emitEvent:false}选项
this.productForm.valueChanges.subscribe(val =>{
if (val.ListPrice > 0 && val.DiscountAmount > 0) {
const newVal = Math.round((val.ListPrice / val.DiscountAmount) * 100);
this.productForm.controls.DiscountPercent.patchValue(newVal, {emitEvent: false});
}
if (val.ListPrice > 0 && val.DiscountAmount > 0) {
const newVal = Math.round((val.DiscountPercent / 100) * val.ListPrice);
this.productForm.controls.DiscountAmount.patchValue(newVal, {emitEvent: false});
}
this.validateForm();
});
}
validateForm() {
Object.keys(this.productForm.controls).forEach(key => {
this.productForm.controls[key].markAsTouched();
this.productForm.controls[key].updateValueAndValidity({emitEvent: false});
});
}