简体   繁体   中英

Angular dynamic FormArray using CVA, child validation not propagated

I am currently dealing with dynamic form arrays in Angular. I have a formArray containing a certain number of controls (to be dynamic:D). When I do push a new control in the array, it gets validated then thanks to the View (html template) a new component - SubFormComponent- is created (via ngFor loop over the formArray controls). Until there, everything is fine. SubFormComponent has a formGroup as class property, containing many formControls. One of that controls ("nom") has a Validators.required set. When the field linked to that control is empty, the whole form should be invalid.

Problem : The thing is, the SubFormComponent's formGroup is indeed invalid but the parent formArray is still valid.

You will find in the following StackBlitz the code to reproduce the "issue". I have added a few logs to track the differents steps. We can see that at the beginning, the formArray gets validated (function validate) then SubFormComponent is created and validated. Unfortunately, the formArray validation process is not called back. The two components involved both use NG_VALIDATOR & NG_ACCESSOR and implements the right methods.

StackBlitz : https://stackblitz.com/edit/angular6-dynamic-form-array-hqzkmq

Do you have any insights on how to solve this?

In my opinion, this is related to the change detection mecanism.

As stated in this answer https://stackoverflow.com/a/56677462/10103986 , you need to call the Change detector when you add a new invalid formControl in your form array.

See this StackBlitz for error resolution : https://stackblitz.com/edit/angular6-dynamic-form-array-wgxp73?file=src/app/app.component.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM