Angular 5 nested template forms.

Giving child components access to the parent form object

Posted on June 19, 2018

The easiest way to give child components access to the parent form object is to add the following to your child component:

import { ControlContainer, NgForm } from '@angular/forms';

@Component( {
	viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
} )

What’s happening here?

Well, when adding a form control in your child component, if no NgForm object exists you’ll be hit with a number of errors.

ControlContainer is a class within NgForm which is called when adding controls – when adding a control using the above code, we’re telling the controller to use the parent NgForm object instead of the non-existent NgForm ControlContainer in the current controller. Simples…