简体   繁体   中英

How can I access a properties of complex nested FormGroup

I am trying to learn reactive forms in Angular. I am able to write to all properties BUT numb, alts, letter and text.

**COMPONENT.TS**

createForm() {
    this.userForm = this.fb.group({
      fname: ['', [Validators.required]],
      lname: ['', [Validators.required]],
      email: ['', [Validators.email, Validators.required]],
      facility: ['', [Validators.required]],
      position: [''],
      test: this.fb.group({
        name: [''],
        id: [''],
        date: [''],
        scored: [''],
        wrong: [''],
        duration: [''],
        answers: this.fb.array ([
          this.fb.group({
            numb: [''],
            alts: this.fb.group({
              letter: this.fb.array([]),
              text: this.fb.array([])
            })
          })
        ])
      })
    })
  }

  get answerArray() {
    return this.userForm.get("answers") as FormArray;
  }
**COMPONENT.HTML**

  <form [formGroup]="userForm">
    <div formGroupName="test">
      <div formArrayName="answers">
        <div *ngFor="let ans of answerArray.controls; let i = index">
          <div [formGroupName]="i">
              <input type="text" formControlName="">
          </div>
        </div>
      </div>
    </div>
  </form>
  <pre>{{ userForm.value | json}}</pre>

I get this error: core.js:6241 ERROR TypeError: Cannot read property 'controls' of null

Please if anyone can help me. I found this example but I was not able to understand https://stackblitz.com/edit/angular-nested-reactive-form-eg-na1ctu?file=src%2Fapp%2Fapp.component.html

Try this one:

get answerArray() {
   return this.userForm.controls['test'].get("answers") as FormArray;   
}

or

get answerArray() {
   return this.userForm.get("test.answers") as FormArray;   
}

or

get answerArray() {
   return this.userForm.get(["test","answers"]) as FormArray;   
}

"answers" is inside "test" that's why its returning undefiend.

Edit: to Access letter or text you can do the following: you must use an index for this one to know which formGroup in the formArray to get.

get textArray(index: number): FormArray {      
  return this.answerArray().at(index).get('alts').get('text') as FormArray;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM