DEV Community

Egor Pavlikhin
Egor Pavlikhin

Posted on

Validation of nested form inputs (within components) in Angular

Mostly writing this for myself, so I don't forget. Google articles for this topic usually show huge walls of text for more complicated cases, but that's not what you'd normally need.

Problem: when you have input fields within a component template the parent form will ignore these fields for validation purposes. So, a structure like this:

-- main.component.ts
<form #angularForm="ngForm">
  <app-nested-inputs></app-nested-inputs>
  <input type="submit" [disabled]="angularForm.form.invalid" />
</form>

-- nested-inputs.component.ts
<input name="xxx" [required]="true" />

The submit button will still be active, even when the form is invalid, unless you add the following to nested-inputs.component.ts Component directive

viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]

So the Component directive will looks like this:

@Component({
  selector: 'nested-inputs',
  templateUrl: './nested-inputs.component.html',
  styleUrls: ['./nested-inputs.component.scss'],
  viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})

Just a little tip to save you a few hours of headache :)

Top comments (0)