How to get Nested formgroup's controls in angular

Angular

Angular Problem Overview


>https://angular.io/api/forms/FormGroup#controls

Follwing my form:

this.form= this.fb.group({
  id: ['', [Validators.required]],
  name: ['', [Validators.maxLength(500)]],
  child: this.fb.group({
    id: [ '', [Validators.required]],
    name: ['']
  })
});

I want to get the validity of child, like this.form.controls.child.controls.valid, while .controls renturn AbstractControl refer to this formgroup api.

angular compile error, error TS2339: Property 'controls' does not exist on type 'AbstractControl'.

Angular Solutions


Solution 1 - Angular

You are close. See code example below or play with it on the very simple (and ugly) StackBlitz I created.

StackBlitz Demo

In your template be sure to add your child form group.

<div>
    <form [formGroup]="myForm" (ngSubmit)="send()">
      <input type="text" name="name" formControlName="name">
      <div formGroupName="child">
         <input type="text" name="id" formControlName="id">
         <input type="text" name="name" formControlName="name">
      </div>
      <button class="btn btn-primary">send</button>
    </form>
  </div>

Then in your component you can access the fields like so.

this.myForm['controls'].child['controls'].id.valid

The reactive form I created for this example:

this.myForm = this.fb.group({
      name: ['', [Validators.maxLength(500)]],
      child: this.fb.group({
        id: ['', [Validators.required]],
        name: ['']
      })
    });

Update Dec 2019

My original answer is a bit dated. There is now a much cleaner way of accomplishing this! Below is example code of the cleaner solution.

this.myForm.get('child.id').valid

Solution 2 - Angular

There are a couple of very simple ways to access the FormControl in a nested FormGroup. From the AbstractControl usage notes:

> Retrieve a nested control > ------------------------- > > For example, to get a name control nested within a person sub-group: > > this.form.get('person.name'); > > -OR- > > this.form.get(['person', 'name']);

Solution 3 - Angular

userForm=new FormGroup({
    fName:new FormControl('',Validators.required),
    lName:new FormControl(),
    eMail:new FormControl('',[Validators.email,Validators.required]),
    qualificationForm:new FormGroup({
     perS:new FormControl(''),
     perHs:new FormControl('')
    })
});

save(){
  console.log(this.userForm.get("qualificationForm.perS").value);
}

Solution 4 - Angular

One way i use alot is to cast the sub formGroup into a form group as the 'get()' method returns an abstractControl and use the 'get()' method to extract the control of the nested formGroup like so :

(this.form.get('child') as FormGroup).get('id').valid

Solution 5 - Angular

I have the following form:

registerLibrarianForm = this.formBuilder.group({
       firstName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(128), Validators.pattern(this.nameRegex)]],
       lastName:  ['', [Validators.required, Validators.minLength(2), Validators.maxLength(128), Validators.pattern(this.nameRegex)]],
       address: this.formBuilder.group({
         country: ['', [Validators.required]],
         city: ['', [Validators.required]]})})

The way I get the controls of the main form (registerForm) is by creating a simple return method:

get controls(){
return this.registerForm.controls;
}

And the way I get the controls of the nested form (address) is by creating another method:

get addressControls(){
return ((this.registerForm.get('address') as FormGroup).controls)
}

So if you need to do a *ngIf in the HTML for the main form use first method

*ngIf="controls.firstName.errors && ...

And for the nested form:

*ngIf="addressControls.country.errors && ...

I hope this might help!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsoulxyView Question on Stackoverflow
Solution 1 - AngularNarmView Answer on Stackoverflow
Solution 2 - AngularThe Gilbert Arenas DaggerView Answer on Stackoverflow
Solution 3 - AngularSusovan KayraView Answer on Stackoverflow
Solution 4 - Angularredd77View Answer on Stackoverflow
Solution 5 - AngularChaviView Answer on Stackoverflow