TemaTre
TemaTre

Reputation: 1424

How to implement Angular Template Driven Forms that contains a lot of Components?

this questions is more about best practice and architecture. I work on project that was writed on angular 2. There are a lot of forms and all this forms are very Big. It is difficult to search something in that. And it's not easy to support that.

When a start to refactor some forms. I split this to list of components (and components are contains another components).

But built-in validation was broken. It was due to Angular isolation and angular awas cannot get errors list from components input elements.

All examples in internet is about reactive forms. I know that it's better to use reactive forms but this is imposible to rewrite all code in one time. And it's not correct to merge both types of forms.

As a solution a make a class that implements ValueAcessor and Validator, and bind Model instead of Input variables. Then inject all childs with NgModel And subscribe to it theirs ngModel.valueChanges.

It seems like control that throws child errors to upper level.

And so the question: Is it correct to create such controls in "Angular philosophy"? So why nobody not implements such solution? (I try to find somethig like this but not found.)

May be there is a some best practice and more correct solutions?

Upvotes: 1

Views: 559

Answers (1)

Grégory Elhaimer
Grégory Elhaimer

Reputation: 2801

ControlValueAccessor is the standard way to implements form component.

It works with both reactivs and template driven forms.

I've tried to handle this kind of component with @Input and it was a mess at the end. Components will only split the code but won't be independant.

Using ControlValueAccessor, you can create a component which only requires a model object. Then, any time you'll need the form component, you won't be stuck with only one type of form (reactiv or template driven) and most importantly, the child component won't drive the way the form has to be built.

Upvotes: 2

Related Questions