When you create complex forms with Angular (out of the realm of demo code), you realize that things that may seem simple on the surface (e.g., “this is just a form with four simple fields”) are not so straightforward to implement (e.g., “ah in fact this field and that field are linked together and there are various business rules to respect; that field is an autocomplete and we want enter/tab to validate the current selection”). The first thing to learn with Angular forms is that
Reactive Forms are the way to go. Template-driven forms are simple, but not great in any way. I’ve covered this in greater length in the
Angular chapter of my TypeScript book. In our project, we’ve decided to create reusable dumb components whenever possible in order to maximize reuse of our code. Applied to complex forms, this means that a complex data structure handled through a form will actually be a composition of multiple components, each handling a specific sub-part of the data model. Composed together, those parts form (pun intended :p) a complex reactive form. One useful Angular construct to be aware of is the ControlValueAccessor, which makes it possible to use dumb components as FormControls, which is terrific!
Kara Erickson has made a few great presentations covering nested forms and ControlValueAccessor, which you can find
here and
there, and also
there. Here are a few awesome resources about CVAs:
Comments ()