Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

angular - 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

question from:https://stackoverflow.com/questions/65602843/how-can-i-access-a-properties-of-complex-nested-formgroup

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

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...