【问题标题】:Reactive forms: Angular formarrays and formcontrols反应式表单:Angular formarrays 和 formcontrols
【发布时间】:2021-02-08 17:31:09
【问题描述】:

假设我有 2 个数组

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

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

【问题讨论】:

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


    【解决方案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>    
    

    【讨论】:

    • 嗨,在你的组件中要小心,你不能调用 this.formControls,因为它是你的 forEach 循环中的一个常量
    • @Twen 感谢您的指出,我首先在组件级别声明它,然后将其移至构造函数。立即更新答案
    猜你喜欢
    • 2019-01-15
    • 2019-06-21
    • 2021-01-12
    • 1970-01-01
    • 2020-05-05
    • 2019-05-04
    • 2017-09-27
    相关资源
    最近更新 更多