4

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

1
  • Where is label in the json? Commented Apr 28, 2020 at 9:54

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

You are welcome, please mark the answer as correct if this was useful.
wondering why it is dynamic, if ".options" is used? Is there a way to solve without hardcoded key?
1

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>

1 Comment

uni_id key itself is dynamic. it can be uni_id5, uni_id7 anything coming from db
1

You can create a variable which will contain name of key:

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

and use this key in HTML template:

<select>
    <option  
       *ngFor=" let item of dynamicData[keyName].options" 
        value="{{item}}">
      {{item }}
    </option>
</select>

It could be seen in stackblitz example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.