首页 > 解决方案 > 如何将项目数组设置为反应式formcontrolName

问题描述

我在一个角度应用程序上工作。

我有一个反应形式,定义为

form!: FormGroup<GlobalBean>

在 globalBean 中,我有另一个 bean 的数组

export interface globalBean{

  /**
   * Version Clé
   */
  terms: AnotherBean[];

在前面的表单为@Input 的组件中,我有以下模板

   <div *ngFor="let term of ######; let index = index;">
      <mat-form-field>
        <mat-label>{{term.property1}}</mat-label>
        <mat-select [formControl]="form"
                    [formControlName]="######"
                    [(value)]="term.property2">
          <mat-option *ngFor="let ta of list2"
                      [value]="ta.valeur">{{ ta.libelle }}</mat-option>
        </mat-select>
      </mat-form-field>
    </div>

我不知道如何在以下两个表达式中定义######:

  1. “让术语######;”
  2. [formControlName]="######"

标签: angularangular-materialangular-reactive-forms

解决方案


您可以尝试以下网站供您参考

https://angular.io/guide/dynamic-form

https://medium.com/@krishnaregmi/how-to-create-dynamic-forms-in-angular-7-using-formcontrol-a443a2c5e3a9

例子:

如果您有 n 项,例如 formValues = [{label: 'a',value:'a'},{label: 'b',value:'b'},{label: 'c',value:'c' }]

你需要先用这个创建你的formGroup

form: FormGroup;
formValues = [{label: 'a',value:'a'},{label: 'b',value:'b'},{label: 'c',value:'c'}]
toFormGroup(arr:any) {
    let group={};
    arr.forEach((x) => {
        group[x.label]=new FormControl(x.value);
    });        
    this.form = new FormGroup(group);
}

这将使用您拥有的动态键创建一个表单组

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <div *ngFor="let element of formValues ">
      <input type="text" formControlName="{{element.label}}" value="{{element.value}}"/>
  </div>  
  <input type="submit" value="save"/>
</form>

我想这会对你有所帮助


推荐阅读