How to make Angular 2 form see injected form controls?

793 Views Asked by At

I'm dynamically injecting a component (using @ViewChild and insert()) with form controls into a component that wraps it with a form tag (so that I can have many different form templates with the same form handling).

This all works fine, but now when I check form.valid, it's always valid because apparently, it doesn't see the form controls that are dynamically injected.

Can I somehow trigger a 'reinitialization' of the ngForm directive on the form so that it will know that there are additional form controls injected?

Note: I do realise by now that a better solution to this problem would probably be to use model driven forms, but right now it's too short notice to redo the whole thing.

Parent template:

<form #htmlFormElement="ngForm" novalidate>
    <div #dynamicComponentContainer></div>
    <!-- more buttons and shared form controls here -->
</form>

Child template E.g.:

<textarea name="comments" [(ngModel)]="formData.comments"></textarea>
1

There are 1 best solutions below

0
On

You can set the viewProviders in the child component to use the existing NgForm as the ControlContainer.

This should automatically treat the form controls in the child component as if they are part of the parent component's form.

e.g:

@Component({
    selector: 'child-with-form-controls',
    templateUrl: './child-with-form-controls.component.html',
    viewProviders: [{ provide: ControlContainer, useExisting: NgForm}]
})
export class ChildWithFormControlsComponent {
    ...
}