简体   繁体   中英

Angular child form control/group values and errors bubbling up to parent

My requirement : A single FormControl must contain the answer of multiple inputs ( multiple child FormControls or FormGroups ).

That is because multiple controls must feed into the top level (parent) FormControl, and the value of the parent level FormControl must be filtered/manipulated to fit the required format.

A good example would be a split up phone input, with a Country code dropdown , phone number input , and extension input , all being separate from one another, but together in a FormGroup. As any of those input values change, the parent level FormControl value must change as well.

In addition to the values bubbling up, the errors of the child controls must bubble up to the parent FormControl too.

Right now I have the parent FormControl listening to the value changes of a FormGroup with the country code, phone number, and extension inputs. Then, using ControlValueAccessor on a component, that writes the value of the parent FormControl when FormGroup ValueChanges.

I need a way to achieve the desired outcome, but also a way to do even more complex controls and FormGroups. Think multiple degrees of nested FormControls and/or FormGroups.

Environment

  • Angular 7
  • Material 7
  • NGRX 6

Initially trying to come up with a nice solution to handle breaking down huge forms into sub forms (sub components...), we came up with a solution for that but also to have access to nested errors.

We've build a library for that https://github.com/cloudnc/ngx-sub-form that will give you way more than just access to nested errors and you can check the official demo here: https://cloudnc.github.io/ngx-sub-form/listings/new (edit the form and see the errors displayed)

I've also replied to a similar SO question here https://stackoverflow.com/a/56375605/2398593 and built a demo for that question here (which also showcase the nested errors functionality) https://stackblitz.com/edit/so-question-angular-2-large-scale-application-forms-handling

Hope it helps!

Edit:

If you want to go further, I've just published a blog post to explain a lot of things about forms and ngx-sub-form here https://dev.to/maxime1992/building-scalable-robust-and-type-safe-forms-with-angular-3nf9

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