Rubel Hosen
Rubel Hosen

Reputation: 309

How to create a dynamic dropown using angular 2?

I want to create some dynamic dropdown menus in the navbar. I have the informations in a javascript object. want to use those data to create the dropdown menus. For example:

let's say I have a javascript object like this:

Food = 
[
  {
    Name : "Fruits",
    Item : 
    { 
      1 : "Apple", 
      2 : "Banana"}
    },
    {
     Name : "Drinks",
     Item : 
     {
        1 : "Milk",
        2 : "Tea"
     }
   }
]

Want to produce something like this

<ul>
  <li>Fruit
    <ul>
      <li>Apple</li>
      <li>Banana</li>
    </ul>
  </li>
  <li>Drink
    <ul>
      <li> Milk </li>
      <li> Tea </li>
    </ul>
  </li>
</ul>

Need help here:

<ul *ngFor = "let f of Food">
    <li>{{f}}
         <ul *ngFor = "let i of Food.Item>
              <li>{{what to put here?}}</li>
         </ul>
    </li>
<ul>

Upvotes: 2

Views: 29

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222702

First of all your JSON is not valid. If you want to make this as a valid JSON, it should be like

[ { "Name": "Fruits", "Item": { "1": "Apple", "2": "Banana" } }, { "Name": "Drinks", "Item": { "1": "Milk", "2": "Tea" } } ]

What you have is an array of Objects, not array of arrays.so you need to access objects using fieldname as follows,

<ul *ngFor = "let f of Food">
    <li>{{f.Name}}
         <ul>
              <li>{{f.Item[1]}}</li>
               <li>{{f.Item[2]}}</li>
         </ul>
    </li>
<ul>

STACKBLITZ DEMO

Upvotes: 1

Related Questions