0
votes

How can I pass the required validator to a nested form? I made a project to explain: https://stackblitz.com/edit/angular-nested-forms-cva-3b17dm?file=src%2Fapp%2Fbasic-info%2Fbasic-info.component.ts

This does not work as expected. Any ideas? Thank you

1

1 Answers

0
votes

Here I consider a userProfile FormGroup as an example You have to access as follows

f.address.controls.city.invalid

.ts file should be like this.

export class Home implements OnInit {
  userProfileForm : FormGroup;

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

}

In the HTML part, it should be edited as follows.

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

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

</form>