How to group the list by date

狂风中的少年 提交于 2019-12-20 04:55:40

问题


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

回答1:


You have to create a custom Pipe for this just like I have done here:

@Pipe({name: 'groupByDate'})
export class GroupByPipe 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] }));
    }  
}

HTML:

<ul>
    <li *ngFor="let group of events | groupByDate">{{group.date}}
        <ul>
            <li *ngFor="let event of group.events">
            {{event.id}} {{event.title}}
            </li>
        </ul>
    </li>
</ul>

I have implemented the solution here: https://stackblitz.com/edit/angular-ldhmnk

Hope it helps.




回答2:


Hello by default you don´t have that pipe but you could find something similar here http://www.competa.com/blog/custom-groupby-pipe-angular-4/



来源:https://stackoverflow.com/questions/51245710/how-to-group-the-list-by-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!