DEV Community

Egor Pavlikhin
Egor Pavlikhin

Posted on

4 2

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 :)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon