2

我有一个问题,因为在我提交表单后,即使有一个值,“必填字段”也不会消失。它应该消失。我的有效性有问题吗?请看这个链接看这个链接

TS

patchValues(id, i) {
let x = (<FormArray>this.addForm.controls['rows']).at(i);

const selectedIngredient = this.ingredients.find(y => y.id == id);

x.patchValue({
  unit_price: selectedIngredient.price
});

}

4

2 回答 2

2

在这些情况下,您必须使用(例如)触发有效性检查:

x.patchValue({
  unit_price: selectedIngredient.price
});
x.get('unit_price').markAsTouched();

修补值时,不会执行验证器。

工作小提琴

于 2018-09-06T07:45:40.520 回答
2

在表单中修补值后,您应该将其标记为已触摸以显示错误

演示

patchValues(id, i) {
   let x = (<FormArray>this.addForm.controls['rows']).at(i);

   const selectedIngredient = this.ingredients.find(y => y.id == id);

   x.patchValue({
     unit_price: selectedIngredient.price
   });
  this.markFormGroupTouched(this.addForm)
}

将完整的表格标记为已触摸:

    /**
     * Marks all controls in a form group as touched
     * @param formGroup - The group to caress
    */
    markFormGroupTouched(formGroup: FormGroup) {
        if (Reflect.getOwnPropertyDescriptor(formGroup, 'controls')) {
            (<any>Object).values(formGroup.controls).forEach(control => {
                if (control instanceof FormGroup) {
                    // FormGroup
                    this.markFormGroupTouched(control);
                } else if (control instanceof FormArray) {
                    control.controls.forEach(c => {
                        if (c instanceof FormGroup)
                            this.markFormGroupTouched(c);
                    });
                }
                // FormControl
                control.markAsTouched();
            });
        }
    }
于 2018-09-06T07:50:58.557 回答