Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the array using a dynamic key in *ngFor : Angular 2+

Tags:

html

angular

This is my object:

dynamicData = 
    {
       uni_id:{options: [1,2,3,4]},
    }

I want to use ngfor loop like this:

<option *ngFor="let opt of dynamicData.uni_id.options" value="{{opt.value}}">{{ opt.label }}</option>

The problem is : uni_id is dynamic and is available at run time. uni_id key itself is dynamic. it can be uni_id5, uni_id7 anything coming from db How can i use it in the template

like image 796
Arunakar Prakash Avatar asked Oct 29 '25 15:10

Arunakar Prakash


2 Answers

You can use keyvalue pipe to dynamically loop through object properties.

Try like this:

  <ng-container *ngFor="let opt of dynamicData | keyvalue">
    <option  *ngFor=" let item of dynamicData[opt.key].options" value="{{item}}">{{item }}</option>
  </ng-container>

Working Demo

like image 100
Adrita Sharma Avatar answered Oct 31 '25 05:10

Adrita Sharma


please use it like this

<option *ngFor="let opt of dynamicData.uni_id?.options" value="{{opt.value}}">{{ opt.label }}</option>

this way you can check if data is there in uni_id then only show

if you are getting dynamic value for uni_id then

in ts file

let uniqueId = Object.keys(this.dynamicData).filter(key => key.startsWith('uni_id'))[0]
list = this.dynamicData.uniqueId

in html file

 <option *ngFor="let opt of list.options" value="{{opt.value}}">{{ opt.label }}</option>
like image 45
Shlok Nangia Avatar answered Oct 31 '25 07:10

Shlok Nangia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!