反应形式:角度形式数组和形式控件

时间:2020-10-26 12:51:13

标签: angular angular-reactive-forms reactive formarray form-control

假设我有2个数组

arraynames['Dog', 'Cat', 'Donkey', 'Bird'];
nrofanimals['10','15', '20', '25'];

为简单起见,现在定义了这两个数组,但实际上可以更改为其他值,依此类推。唯一的约束是两个数组必须具有相同的大小。我想要的是我想为每个名称的动物数量创建一个formcontrol。我的意思是我要在localhost:4200中显示带有mat-label“ Dog”的mat-form-field,带有mat-input“ 10”,以及另一个带有mat-label“ Cat”的mat-form-field。 -输入“ 15”,依此类推。我怎样才能做到这一点?请记住,我仅将这两个数组作为示例。在我的情况下,数组将由用户填充,因此我不能具有预定义的数组。预先感谢。

1 个答案:

答案 0 :(得分:1)

检出Angular Dynamic FormsFormArrayFormGroup,以了解用例所需的基本概念。

基本概念证明如下:

import { Component, Input } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
    
@Component({
  selector: 'app-animals',
  templateUrl: './dynamic-form-question.component.html'
})

export class AnimalsComponent {
  
  animalForm: any; 

  constructor(){
    const formControls = {};
      arraynames.forEach((animal,index)=>{  //iterate over your animal's array
        formControls['animal'] = new FormControl(nrofanimals[index]); //create a new form control for each animal and set the value of formcontrol via index from no array
        });
        this.animalForm = formControls; //assign the object to the formGroup variable 
      }
  }
}    

然后创建您的html模板,并在动物名的数组上进行迭代,将动物名设置为formControlName,这样您就可以动态生成字段;

<form  [formGroup]="animalForm"> 
    
   <div *ngFor="let animal of arraynames;">
       <mat-form-field>
           <label>{{animal}}</label>
           <input  [formControlName]="animal">      
        <mat-form-field>
    </div>
    
    <div class="form-row">
        <button type="submit">Save</button>
    </div>

</form>