在模板中获取Angular formArrayName索引值

时间:2019-11-25 09:20:20

标签: angular formarray

在访问模板中的Angular formArray对象值时需要帮助。我可以在formArray组中添加和删除项目

最小示例

组件文件

...
import { FormControl, FormGroup, FormBuilder, FormArray } from '@angular/forms';

form: FormGroup;
constructor(private fb: FormBuilder) { }

ngOnInit(): void {
  this.form = this.fb.group({
    candidateNumber: '',
    subjectGrade: this.fb.array([])
  })
}

get subjectGradeForms() {
  return this.form.get('subjectGrade') as FormArray
}

addSubjectGrade() {
  const subjectGrade = this.fb.group({
    subject: [],
    grade: []
  })
  this.subjectGradeForms.push(subjectGrade);
}

removeSubjectGrade(i) {
  this.subjectGradeForms.removeAt(i)
}

HTML模板文件

...
<form class="kt-form" id="kt_form" [formGroup]='form'>
  <div class="form-group">
    <label for="candidateNumber">Candidate Number</label>
    <input formControlName="candidateNumber" class="form-control" type="text" required=""> 
  </div>

  <div class="row" formArrayName='subjectGrade'>
    <div class="row" *ngFor="let subjectGrade of subjectGradeForms.controls; let i=index;" [formGroupName]="i">
      <div class="form-group">
        <label for="subject">Subject Name</label>
        <select class="form-control" formControlName="subject" required="">
          <option *ngFor="let subject of subjectNames" [value]="subject">{{ subject }}</option>
        </select>
      </div>

      <div class="form-group">
        <label for="grade">Subject Grade</label>
        <select class="form-control" formControlName="grade" required="">
          <option *ngFor="let grade of subjectGrades" [value]="grade">{{ grade }}</option>
        </select>
      </div>
    </div>
  </div>
</form>

挑战/问题部分[在HTML模板文件中]

<div class="kt-wizard-v2__review-content">
  Candidate Number: {{ form.value.candidateNumber }}<br/>  <!-- works as desired with right output-->
  Subject: {{ subjectGrade.value.subject[0] }}<br/>  <!-- does NOT works as desired gives tscript error -->
  Subject: {{ subjectGrade[0].subject }}<br/>  <!-- does NOT works as desired gives tscript error -->
  Subject: {{ form.value.subject[0] }}<br/>  <!-- does NOT works as desired gives tscript error -->
  Subject: {{ form.value.subjectGrade[0].subject }}<br/>  <!-- does NOT works as desired gives tscript error -->
  Subject: {{ form.value.subjectGrade }}<br/>  <!-- does NOT works as desired gives tscript object as output -->
</div>

表单值输出

value: {{ form.value | json }}
value: {"candidateNumber": "12000", 
        "subjectGrade": [ { "subject": "axb", "grade": "b" }, { "subject": "bxb", "grade": "b" } ] 
       } 

感觉我缺少一些基本知识,但是我看不到什么。

EDIT 来自此form.value | json输出

{"candidateNumber": "12000", 
 "subjectGrade": [ { "subject": "axb", "grade": "b" }, 
                   { "subject": "bxb", "grade": "b" } ]
} 

我希望能够 获取“主题”键的值 “等级”键。

因此,Subject: {{ what_ever_is_here }}应该输出axb,而Grade: {{ what_ever_is_here }}应该输出b [至少是第一次迭代]

2 个答案:

答案 0 :(得分:0)

不是您的索引,在此行:

 <div class="row" *ngFor="let subjectGrade of subjectGradeForms.controls; let i=index;" [formGroupName]="i">

那个i

然后必须添加调用该函数的按钮,该函数将删除该ngfor块下的项目并调用:

removeSubjectGrade(i)

这是您的意思,还是组件功能的问题?

答案 1 :(得分:0)

这就是我在代码中为复选框实现FormArray的方式,
HTML

<div formArrayName="healthQuestions">
                <div
                  *ngFor="let questionControl of cdqRequestFG.controls.questions.controls.healthQuestions.controls; let i=index;"
                  nxRow>
                  <div class="centre-align" nxCol="12,6,4,3">
                    <nx-radio-group [formControlName]="i" style="display: flex;">
                      <nx-radio style="padding:15px;" [labelSize]="'small'" nxValue="YES">yes
                      </nx-radio>
                      <nx-radio style="padding:15px;" [labelSize]="'small'" nxValue="NO">No
                      </nx-radio>
                    </nx-radio-group>
                  </div>
                  <div nxCol="12,6,8,9">
                    <p style='font-size:18px; text-align: left'>{{i+1}} - {{rgaQuestions[i].description}}</p>
<!-- to display the contents of rgaQuestions, to display question number i+1 used since index begin at 0-->
                  </div>
                </div>
              </div>

Component.ts

healthQuestionsFC: FormArray;
this.healthQuestionsFC = new FormArray([], Validators.required);

// read the arry result to Model Array
//the array items are stored in array rgaQuestions[], user response for each item in this array is obtained from below loop
this.rgaQuestions.forEach(
      (val, index) => {
//      **getting Index value from template**
        const ansC = this.healthQuestionsFC.get(index + '');
        const question = new QuestionResp(val.questionId + '', ansC.value);
        questionList.push(question);
      });

//clear the array
clearFormArray = (formArray: FormArray) => {
    while (formArray.length !== 0) {
      formArray.removeAt(0);
    }
  }