Home > Back-end >  How to pass Object/Array as variable to NgFor in a dynamic Select control?
How to pass Object/Array as variable to NgFor in a dynamic Select control?

Time:05-06

I am creating a dynamic form using few examples. All good if I have the static option values defined in the template for Select component. But since it is dynamic, i want to render select options from a method.

<div*ngFor="let control of FormData.controls">
<mat-select [formControlName]="control.name">
<mat-option *ngFor="let item of Countries">item.name</mat-option>
</mat-select>
</div>

now i want to make this dymaic for States, fruits etc

*ngFor="let item of 'Countries'"

any ways to make it dynamic and driven this from json template

CodePudding user response:

Did you creating an object and having the arrays in a key value pair like below,

myNewObj = {}
**somewhere in my code**
this.myNewObj = {
  array1:['data1', 'data2'],
  array2:['data3', 'data4']
}

In HTML

<div *ngFor="let item of myNewObj['array1']">
   {{item}}
</div>

CodePudding user response:

You need to Add value inside the mat-option.

<div*ngFor="let control of FormData.controls">
    <mat-select [formControlName]="control.name">
    <mat-option *ngFor="let item of Countries" [value]="item.name">item.name</mat-option>
    </mat-select>
    </div>
  • Related