Angular reactive form validate nested fields

Viewed 4240

I'm using Angular 7

I have a nested reactive form

this.salonProfileForm = this.fb.group({
  salonName: new FormControl('', [Validators.required]),
  address: this.fb.group({
    city: new FormControl('', [Validators.required])
  })
});

get f() {
    return this.salonProfileForm.controls;
}

And I have the HTML form like

<input type="text" formControlName="salonName" required />
<ng-container *ngIf="submitted && f.salonName.invalid && (f.salonName.dirty || f.salonName.touched)">
   <small *ngIf="f.salonName.errors.required">
      Salon name is required
   </small>
</ng-container>

<div formGroupName="address">
  <input type="text" formControlName="city" />
  <ng-container *ngIf="submitted && f.city.invalid && (f.city.dirty || f.city.touched)">
    <small *ngIf="f.city.errors.required">
        city is required
    </small>
  </ng-container>
</div>

But this gives error on city input ng-container field as

ERROR TypeError: Cannot read property 'invalid' of undefined

How can I validate the nested input fields?

console.log(this.f.address)

enter image description here

1 Answers

You have to access like following:

f.address.controls.city.invalid

Edit

export class Home implements OnInit {
  salonProfileForm : FormGroup;

  ngOnInit() {
    this.salonProfileForm = new FormGroup({
      'salonName': new FormControl('', [Validators.required]),
      'address': new FormGroup({
        'city': new FormControl('', [Validators.required])
    })
  });
 }

}

Moving to .html template

<form [formGroup]="salonProfileForm " (ngSubmit)="onSubmit()">

<div formGroupName="address">
  <input type="text" formControlName="city" />
  <ng-container *ngIf="!salonProfileForm.get('address.city').valid && salonProfileForm.get('address.city').touched">
    <span>This is required</span>
  </ng-container>
</div>

</form>

I have pasted in shape it works , So feel free to update your code to fit the above.

Related