2

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

}

1
  • Try using x.updateValueAndValidity() after patching the value. Commented Sep 6, 2018 at 7:44

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

After patching values in form you should mark it touched to display errors

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

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

12 Comments

i have given demo check it
Haha again you answered later than Cetia. Anyway i upvoted you
Hey can i ask for help. I added quantity in my code. How come it isnt valid when i set it to [0, Validators.required]?
Hello did younget it?
Yes I will give u answer wait .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.