Angular 6 Nested FormGroup Template Validation

Alex Mohr picture Alex Mohr · Jul 21, 2018 · Viewed 8.4k times · Source

My form group structure looks like this (order.component.ts):

this.orderForm = this.formBuilder.group({
  customer: this.formBuilder.group({
    name: ['', Validators.required],
    phone: ['', Validators.required],
    email: ['', Validators.required]
  }),
  ...
});

In the template (order.component.html) I have:

<form [formGroup]="orderForm" (ngSubmit)="onSubmit()">
  <fieldset formGroupName="customer">
    <legend>Customer Information</legend>
    <label for="name">Full name:</label>
    <input type="text" formControlName="name" class="form-control" name="name" id="name" required>
    <small class="form-text text-danger" *ngIf="orderForm.controls['customer'].controls['name'].invalid && (orderForm.controls['customer'].controls['name'].dirty || orderForm.controls['customer'].controls['name'].touched)">Name invalid</small>
  </fieldset>
  ...
</form>

This works, but is a shorter way of expressing orderForm.controls['customer'].controls['name']? For example it would be more succinct for the *ngIf condition to be "name.invalid && (name.dirty || name.touched)"

Answer

Amit Chigadani picture Amit Chigadani · Jul 21, 2018

Yes, that is the correct way to fetch nested form Control and no shortcut.

or you could create some property in your component which points to orderForm.get('customer') form object

private customerForm : FormGroup

And assign it after form initialization

this.customerForm = this.orderForm.get('customer')

and fetch it like {{customerForm.get('name').valid}}