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?

1

1 Answer 1

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.

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

1 Comment

this was helpful, just to add on isn't this.newSubcategories.push(a); supposed to be this.newSubcategories.push(item);

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.