How do I use ngFor with a Javascript dictionary?

Asked

Viewed 58 times

2

I’m trying to generate a dynamic page with Angular 9, my idea is every key in the dictionary create an optgoup tag and each value an option, but I’m not able to access the values of the Dict object.

Code:

  <optgroup *ngFor="let categoria in categorias" [label]="categoria">
    <option *ngFor="let valor in categorias[categoria]" >{{ valor }}</option>
  </optgroup>

Example:

// Dict
var categorias = {
  "Pediatra": ["Igor", "Luiz", "Ricardo"],
  "Ortopedista ": ["João", "Lucas", "Julia"]
};

Upshot:

<optgroup label="Pediatra">
   <option>Igor</option>
   <option>Luiz</option>
   <option>Ricardo</option>
</optgroup>
<optgroup label="Ortopedista">
   <option>João</option>
   <option>Lucas</option>
   <option>Julia</option>
</optgroup>
  • Does an error occur or just doesn’t go out as expected?

  • No error occurred, Angular generated the build and showed the empty optgroup tag. But the Geeksilva response worked well.

1 answer

4


Cannot iterate on Object. Trying to do this on JS you will get the error Uncaught TypeError: a is not iterable.

In your case here what you could solve was to have an array of Keys and iterate over that array.

Would then:

// Dict
let categorias = {
  "Pediatra": ["Igor", "Luiz", "Ricardo"],
  "Ortopedista ": ["João", "Lucas", "Julia"]
};

// keys list
let categoryKeys = Object.keys(categorias);

There in HTML you could do

<optgroup *ngFor="let categoria of categoryKeys" [label]="categoria">
    <option *ngFor="let valor of categorias[categoria]" >{{ valor }}</option>
</optgroup>

So at first *ngFor you have the loop in the array ['Pediatra', 'Ortopedista'] and in the second you do based on the category why is going to key for the dictionary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.