2016-08-07 39 views
0
var cities = [{id: 1, name: "London"}, {id:2, name="manchester"}] 
var areas = [{name="Buckingham palace", cityId: 1}, {name:"Wembley", cityId:1}, {name:"Media City", cityId: 2}, {name:"Old Trafford", cityId:2}] 

我怎樣才能讓一個列表中出現,像這樣:angular2加入陣列和過濾

London 

Buckingham palace 

Wembley 

Manchester 

Media City 

Old Trafford 

到目前爲止,我有:

<ion-list> 
    <ion-item *ngFor="let category of categories"> 
    {{category.name}} 
    </ion-item> 
    <ion-list> 
     <ion-item *ngFor="let area of areas"> ### HERE: Where area.id == category.id 
      {{area.name}} 
     </ion-item> 
    </ion-list> 
</ion-list> 

我似乎卡住匹配的項目,研究表明沒有真正明確的方法來做到這一點。隨着其他項目的添加,平坦化數據並不好。

嵌套循環的任何想法或最佳做法匹配的ID?

+0

您可以創建一個管道,過濾。請參閱http://stackoverflow.com/questions/34164413/how-to-apply-filters-to-ng這是舊版本,但應該是類似的實施。 –

+0

對angular2語法不太熟悉,但可以使用'groupBy'過濾器 –

回答

1

感謝@Arpit您的建議我去這下面採用了最新的angular2(7 - 8 - 16):

import { Injectable, Pipe } from '@angular/core'; 
@Pipe({  
    name: 'whereCatId', 
    pure: false 
}) 
@Injectable() 
export class WhereCatId { 
    transform(cities: any, catId: any){ 
    let matched = []; 
cities.forEach((city) => { 
    if(city.category.id == catId){ 
     matched.push(city);  
    } 
}); 
return matched; 
    } 
} 

然後在我的頁面添加的參考管文件,並在包括它@Component

,並要求它像

 <ion-item *ngFor="let area of areas | whereCatId:place.id"> 
+0

好我可以幫忙。 –