I am trying to show list with group by date using below code but i am getting exceptions Unable to get property 'forEach' of undefined or null reference can some one help me please where did i do mistack
home.ts:
this.events = [{
id: 1,
category:'camera',
title: 'First event',
date: '2017-12-26'
}, {
id: 2,
category:'accessories',
title: 'Second event',
date: '2017-12-27'
}, {
id: 3,
category:'camera',
title: 'Third event',
date: '2017-12-26'
}, {
id: 4,
category:'accessories',
title: 'Fouth event',
date: '2017-12-27'
},{
id: 5,
category:'camera',
title: 'Fifth event',
date: '2017-12-26'
}]
}
home.html:
<ion-content padding>
<ion-item-group *ngFor="let group of events | groupBy: 'date'">
<ion-item-divider color="light">
{{ group.date }}
</ion-item-divider>
<ion-item *ngFor="let event of group.events">{{ event.title }}</ion-item>
</ion-item-group>
</ion-content>
GroupByDate:
@Pipe({name: 'groupByDate'})
export class GroupByPipeProvider implements PipeTransform {
transform(collection: Array<any>, property: string = 'date'): Array<any> {
if(!collection) {
return null;
}
const gc = collection.reduce((previous, current)=> {
if(!previous[current[property]]) {
previous[current[property]] = [];
}
current.events.forEach(x => previous[current[property]].push(x));
return previous;
}, {});
return Object.keys(gc).map(date => ({ date: date, events: gc[date] }));
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…