Angular Form validation on child components

For future googlers,

I had a similar issue to this, albeit with fewer child components and after digging through @penleychan's aforementioned thread on the subject I found a little gem that solved this for me without the need to implement a custom directive.

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

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

This works for my nested form. Just needs to be added to components, which ones directly contains inputs

https://github.com/angular/angular/issues/9600#issuecomment-522898551


Hope i'm not too late. I recently stumbled on this issue too with template approach since reactive form did not fit what I needed to do...

The issue is something to do with ControlValueAccessor that your component need to implement. However I couldn't get that working.

See: https://github.com/angular/angular/issues/9600

Solution provided by andreev-artem works well, and I also added my solution to wrap it inside ngModelGroup instead of in the form's root object controls property.

For your case you're not using ngModelGroup you could just have this directive

@Directive({
selector: '[provide-parent-form]',
providers: [
    {
        provide: ControlContainer,
        useFactory: function (form: NgForm) {
            return form;
        },
        deps: [NgForm]
    }
  ]
})
export class ProvideParentForm {}

Usage: In your component at the root element before you have [(ngModel)] add the directive. Example:

<div provide-parent-form> 
   <input name="myInput" [(ngModel)]="myInput"> 
</div>

Now if you output your form object in your console or whatever you can see your component's controls under controls property of your form's object.