Reputation: 7755
I've a problem because after i submit the form, even though there's a value, the "field is required" doesn't disappear. It supposed to disappear. Is there something wrong with my validity? Please see this link See 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
});
}
Upvotes: 2
Views: 3397
Reputation: 14440
In these cases, you have to trigger a validity check with (for example) :
x.patchValue({
unit_price: selectedIngredient.price
});
x.get('unit_price').markAsTouched();
When patching a value, validators aren't executed.
Working fiddle
Upvotes: 2
Reputation: 7231
After patching values in form you should mark it touched to display errors
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)
}
To mark complete form as touched:
/**
* 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();
});
}
}
Upvotes: 2