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

angular - How to set an array of items as reactive formcontrolName

I work on an angular application.

I have a reactive form which is defined as

form!: FormGroup<GlobalBean>

In the globalBean, I have an array of another bean

export interface globalBean{

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

In a component that has the preceeding form as @Input, I have the following template

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

I don't know how to define ###### in the two following expression :

  1. "let term of ######;"
  2. [formControlName]="######"
question from:https://stackoverflow.com/questions/65909628/how-to-set-an-array-of-items-as-reactive-formcontrolname

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

1 Reply

0 votes
by (71.8m points)

You can try below site for your reference

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

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

Example:

If you are having n items like formValues = [{label: 'a',value:'a'},{label: 'b',value:'b'},{label: 'c',value:'c'}]

You need to create your formGroup with this first

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);
}

this will create a formgroup with dynamic keys you have

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

I think this will help you


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

...