Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

How to get Nested formgroup's controls in 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'.

question from:https://stackoverflow.com/questions/49269403/how-to-get-nested-formgroups-controls-in-angular

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...