How to make Angular parent FormGroup invalid until all nested FormGroups are valid

334 Views Asked by At

I have a FormGroup containing nested FormGroups. I want to put a validator on the BasicInfo child FormGroup (on FirstName control) using the code below. However, I want to disable the submit button if the entire parent form group is invalid. If any of the children are invalid, it should be invalid until all children are valid. But this is not happening on initial load. It only happens if I touch any of the child input elements.

stackblitz link

user-registration.component.ts (parent component). First name should be required

 .....
  this.userForm = this.fb.group({
  basicInfo: this.fb.group({
    firstName: [],
    lastName: [],
    email: [],
    age: []
  }),
  .....

basic-info.component.ts

  //setting required firstName
  ngAfterViewInit(){
    this.form.get('firstName').setValidators(Validators.required)
    this.form.updateValueAndValidity()
  }

basic-info.component.html enter image description here

Parent form always returns true on initial load. The submit button should be disabled if the firstName is blank. Parent form always returns true on initial load

1

There are 1 best solutions below

0
Stefani Toto On

this.form.controls["firstName"].addValidators([Validators.required]);