Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Nested formgroup's controls in angular

Tags:

angular

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'.

like image 737
soulxy Avatar asked Mar 14 '18 03:03

soulxy


People also ask

What is nested form in Angular?

What is a Nested Form? In simple words, nested forms are forms within a form. Using nested forms, we can create an array of objects within a single field and we can have an array of these fields. Hence, the nested form helps us manage large form groups and divides it into small groups.

What is FormArray in Angular?

A FormArray aggregates the values of each child FormControl into an array. It calculates its status by reducing the status values of its children. For example, if one of the controls in a FormArray is invalid, the entire array becomes invalid.


2 Answers

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']);

like image 32
The Gilbert Arenas Dagger Avatar answered Sep 18 '22 08:09

The Gilbert Arenas Dagger


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

like image 112
Narm Avatar answered Sep 21 '22 08:09

Narm