Angular 9 How to generate reactive form controls automatically from indexes extracted from an array of data?

允我心安 提交于 2020-06-28 03:58:10

问题


I am trying to create a reactive form from indexes extracted from an array of data.

Lets say I have the following array:

array = [
  { name: 'Ali', gender: 'Male' },
  { name: 'Sara', gender: 'Female' }
];

I extracted the index as following:

this.result = new Set(this.array.flatMap(e => Object.keys(e), []));
this.result = Array.from(this.result);

And the result:

console.log(this.result)
// ["name", "gender"]

Now I need to loop over this.result and create 2 form control names with formControlName='name' and for gender as well.

Once the loop is done and the form controls are created, I need to display it on screen. Here is a stackblitz about it.


回答1:


you can simple create a formGroup base of the array values now fieldFormItems will be an array of formGroups

component

  createForm() : void{
    this.fieldForm = this.formBuilder.group({
      fieldFormItems: this.formBuilder.array(
        this.array.map(values =>{
          return this.formBuilder.group(values)
        })
      )
    })
  }

template

<div [formGroup]="fieldForm">
    <div formArrayName="fieldFormItems">
      <div *ngFor="let fg of fieldForm.get('fieldFormItems').controls" [formGroup]="fg" >
          <input formControlName="name">
          <input formControlName="gender">
      </div>
    </div>
</div>

Updated

get the form controls dynamically 🧙‍♂️

div [formGroup]="fieldForm">
    <div formArrayName="fieldFormItems">
        <div *ngFor="let fg of fieldForm.get('fieldFormItems').controls" [formGroup]="fg">
            <ng-container *ngFor="let fc of fg.controls | keyvalue">
                <input type="text" [formControl]="fc.value">
      </ng-container>
    </div>
    </div>
</div

demo 🚀



来源:https://stackoverflow.com/questions/60925681/angular-9-how-to-generate-reactive-form-controls-automatically-from-indexes-extr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!