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
711 views
in Technique[技术] by (71.8m points)

angular - How to Using a FormArray in a FormGroup

html file

<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([])

});

this is the error show am new to angular somebody please help me to resolve this. is Something i missed in this code?

ERROR Error: Cannot find control with path: questions -> 0 at _throwError (forms.js:3357)at setUpControl (forms.js:3181)at FormGroupDirective.addControl (forms.js:7345)at FormControlName._setUpControl (forms.js:8070)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

1.-When you use ReactiveForms, not use [(ngModel)] (is valid the "isIndividualMark" because this not belong to the formGroup

2.-A formArray can be a FormArray of FormGroups or a FormArray of FormControls

A formArray of formGroups value will be in the way

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

A formArray of formControls value will be in the way

["one","two"]

3.-When we has a FormArray we use a getter to return the formArray

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

Well, you has a formArray of formControls so the way is always the same

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

BTW: if we has a formArray of FormGroup the way is a bit different

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

Update If we want to give a value to the formGroup we use pathValue, some like

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

The problem with pathValue (or setValue) is that we need add so many elements to the formArray, so we need make some like

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

Well, exist another option I personal like, that is to make a function that return the formGroup -with data or with default values-. Some like

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)):
                  [])
    });

See that if we has an object we can do

this.sectionForm=this.createGroup(myObject)

And if you want an empty formGroup

this.sectionForm=this.createGroup()

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

...