首页 > 解决方案 > 如何在 FormGroup 中使用 FormArray

问题描述

.html 文件

<form #form="ngForm" [formGroup]="sectionForm" #formDirective="ngForm" (ngSubmit)="setSections(sectionForm.value,null,formDirective)">


  <div fxLayout="row wrap" style="padding: 0px 16px;">
    <mat-checkbox class="example-margin" [(ngModel)]="isIndividualMark" [ngModelOptions]="{standalone: true}" (ngModelChange)="modelChangeFn($event)">
      Individual Mark
    </mat-checkbox>
  </div>

  <div formArrayName="questions" style="min-height: 100px;max-height: 100px;overflow: auto;">
    <div fxLayout="row wrap" class="list" *ngFor="let questions of selectedQn  trackBy: let selected_qn_index = index;">

      <div id="form" fxFlex="100" fxFlex.gt-sm="50" fxFlex.gt-md="20" fxLayoutAlign="end center">

        <span>
          <mat-form-field *ngIf="isIndividualMark" style="text-align: right;width: 25px;">

            <input type="number" maxlength="3" min="1" matInput [(ngModel)]="questions.qn_mark" [formControlName]="selected_qn_index">
            <!-- <input min="0" type="number"  matInput formControlName="mark_ind_qn">
                        <mat-error>{{error}}</mat-error> -->
            <mat-error *ngIf="!questions.qn_mark || questions.qn_mark==0">
              {{"error"}}
            </mat-error>

          </mat-form-field>
        </span>

      </div>
    </div>
  </div>

  <div fxLayout="row wrap" style="padding: 16px;" fxLayoutAlign="end center">
    <div style="font-size: 16px;font-weight: 900;">
      <span style="padding: 5px;">
        <button mat-raised-button color="accent" [disabled]="!sectionForm.valid">
          Add Section
        </button>
      </span>
    </div>
  </div>
</form>

TS

this.sectionForm = new FormGroup({
  name: new FormControl('', [Validators.required]),
  instruction: new FormControl('', [Validators.required]),
  mark_each_qn: new FormControl(),
  questions: new FormArray([])

});

这是错误显示是新的角度有人请帮我解决这个问题。我在这段代码中错过了什么?

错误错误:找不到带有路径的控件:问题-> 0 at _throwError (forms.js:3357) at setUpControl (forms.js:3181) at FormGroupDirective.addControl (forms.js:7345) at FormControlName._setUpControl (forms.js :8070)

标签: angulartypescriptform-control

解决方案


1.-当您使用 ReactiveForms 时,不要使用 [(ngModel)](“isIndividualMark”是有效的,因为这不属于 formGroup

2.-一个formArray可以是FormGroups的FormArray或者FormControls的FormArray

formGroups 值的 formArray 将成为障碍

[{id:1,name:"one"},{id:2,name:"two"}]

formControls 值的 formArray 将成为障碍

["one","two"]

3.-当我们有一个 FormArray 时,我们使用 getter 来返回 formArray

get questionArray(){
   return this.sectionForm.get('questions') as FormArray
}

好吧,你有一个 formArray 的 formControls 所以方式总是一样的

<!--a div with formArrayName-->
<div formArrayName="questions">
    <!--iterating over the formArray.controls using the getter-->
    <div *ngFor="let control of questionArray.controls;let i=index">
        <!--you can use the "i" to get the value of an array,e.g.-->
        {{label[i]}}
        <!--a input with formControlName-->
        <input [formControlName]="i">
    
    </div>
</div>

顺便说一句:如果我们有一个 FormGroup 的 formArray 方式会有点不同

<!--a div with formArrayName-->
<div formArrayName="questions">
    <!--iterating over the formArray.controls using the getter-->
        and use [formGroupName]
    <div *ngFor="let control of questionArray.controls;let i=index"
            [formGroupName]="i">

        <!--the inputs with formControlName, see that in this case 
            is not enclosed by []-->
        <input formControlName="id">
        <input formControlName="name">
    
    </div>
</div>

更新如果我们想给 formGroup 一个值,我们使用 pathValue,有些像

this.sectionForm = new FormGroup({...})
this.sectionForm.pathValue(myObject) //<--be carefull if we has a formArray

pathValue(或 setValue)的问题是我们需要向 formArray 添加这么多元素,所以我们需要做一些类似

this.sectionForm = new FormGroup({...})
this.myobject.questions.forEach(_=>{
    this.questionArray.push(new FormControl())
}
this.sectionForm.pathValue(myObject) //Now yes!

好吧,存在我个人喜欢的另一个选项,即创建一个返回 formGroup 的函数 - 带有数据或默认值 -。有些喜欢

createGroup(data:any=null)
    data=data || {name:'',instruction:'',mark_each_qn:false,questions:null}
    return new FormGroup({
      name: new FormControl(data.name, [Validators.required]),
      instruction: new FormControl(data.instruction, [Validators.required]),
      mark_each_qn: new FormControl(data.mark_each_qn),
      questions: new FormArray(data.questions?
                  data.question.map(x=>new FormControl(x)):
                  [])
    });

看看如果我们有一个我们可以做的对象

this.sectionForm=this.createGroup(myObject)

如果你想要一个空的 formGroup

this.sectionForm=this.createGroup()

推荐阅读