修补项目不会更新 Angular 中的有效性

Patching Items Doesn't Update Validity in Angular

我遇到了一个问题,因为在我提交表单后,即使有一个值,"field is required" 也没有消失。它应该消失。我的有效性有问题吗?请看这个linkSee this link

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

}

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

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

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

工作fiddle

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

DEMO

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