2

I´m trying to loop over a content. I tried some answers found here in StackOverflow but none works for me.

I have this JSON

{  
   "-KmdNgomUUnfV8fkzne_":{  
      "name":"Abastecimento"
   },
   "-KmdNgzguGKbCEfyQ3F0":{  
      "name":"Consórcios"
   },
   "-KmdNh9_jtBlFqY1Y_Rj":{  
      "name":"Consultoria aeronáutica"
   },
   "-KmdNhKNCVEiJ2Ou8bUV":{  
      "name":"Cursos e treinamentos"
   },
   "-KmdNhVRoKfaCM--304M":{  
      "name":"Financiamento"
   },
   "-KmdNhfIC6fA0kDJcVBq":{  
      "name":"Hangaragem"
   },
   "-KmdNhu0X-PteQMyHp_n":{  
      "name":"Mecânica"
   },
   "-KmdNi6ZmmYXnoOTXoC5":{  
      "name":"Táxi Aéreo"
   },
   "-KmdNiHFhiX_crXB1L2R":{  
      "name":"Outros"
   }
}

I´m trying to loop using this code

<button ion-item *ngFor="let cat of subcategories" (click)="onSubcategorySelect(cat)">
              {{ cat.name }} 
</button>

It's not working. What am I doing wrong?

glennsl
  • 28,186
  • 12
  • 57
  • 75
Andre Pavini
  • 343
  • 4
  • 18
  • Take a look at this - https://stackoverflow.com/questions/41396435/how-to-iterate-object-object-using-ngfor-in-angular-2 – Philip Brack Oct 16 '17 at 16:13

1 Answers1

5

Angular's ng-for requires any element with Iterable interface to work and it's not the case for a plain Object. You need to "convert" this object in an array, the easier way is with forEach or a for/in loop:

Anywhere in your code you'll iterate through your object and save it in a new variable to be used in ngFor:

public newSubcategories: any[] = []; // DECLARE A NEW EMPTY ARRAY IN THE TOP OF YOUR CLASS

this.subcategories.forEach(item => {
  this.newSubcategories.push(a);
});

If you need to mantain the key use for/in to push a new object with the key.

public newSubcategories: any[] = []; // DECLARE A NEW EMPTY ARRAY IN THE TOP OF YOUR CLASS

for(let key in this.subcategories){
  this.newSubcategories.push({
    key: key,
    name: this.subcategories[key].name
  });
}

Finally your HTML

<button ion-item *ngFor="let cat of newSubcategories" (click)="onSubcategorySelect(cat)">
  {{ cat.name }} 
</button>

With this you'll be able to use ng-for in your new array.

Hope this helps.

Gabriel Barreto
  • 6,411
  • 2
  • 24
  • 47
  • this was helpful, just to add on isn't `this.newSubcategories.push(a);` supposed to be `this.newSubcategories.push(item);` – dxt Jun 15 '19 at 16:13