循环遍历对象Ionic3/Angular4 [英] Loop over object Ionic3/Angular4

查看:239
本文介绍了循环遍历对象Ionic3/Angular4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历内容.我尝试了一些在StackOverflow中找到的答案,但是没有一个适合我.

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

我有这个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?

推荐答案

Angular的ng-for要求具有Iterable接口的任何元素都可以工作,而普通对象不是这种情况.您需要在数组中转换"该对象,更简单的方法是使用forEachfor/in循环:

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:

在代码中的任何地方,您都将遍历对象,并将其保存在要在ngFor中使用的新变量中:

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);
});

如果您需要保留钥匙,请使用for/in用钥匙推入新对象.

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
  });
}

最后是您的HTML

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

通过此操作,您将可以在新阵列中使用ng-for.

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

希望这会有所帮助.

这篇关于循环遍历对象Ionic3/Angular4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆