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}]

How can I make a list appear like so:

London

Buckingham palace

Wembley

Manchester

Media City

Old Trafford

So far I have:

<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>

I seem to get stuck matching the items, and researching shows no real clear way to do this. It's not good to flatten the data either as other items are appended later.

Any thoughts or best practices on nested loops matched by id's?

dale
  • 1,258
  • 2
  • 17
  • 36
  • You can create a pipe to filter it. See http://stackoverflow.com/questions/34164413/how-to-apply-filters-to-ngfor this is on old release but should be similar implementation. – Arpit Agarwal Aug 07 '16 at 09:14
  • Not really familiar with angular2 syntax but you can use `groupBy` filter – Evans Murithi Aug 07 '16 at 09:26

1 Answers1

1

Thanks @Arpit for your suggestion i went with this below using the latest angular2 (7-aug-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;
  }
}

Then in my page added the reference to the pipe file and included it in the @Component

and called it like

        <ion-item *ngFor="let area of areas | whereCatId:place.id">
dale
  • 1,258
  • 2
  • 17
  • 36