如何按日期分组列表

时间:2018-07-09 12:33:32

标签: angular ionic-framework ionic3

我正在尝试使用以下代码显示按日期分组的列表,但我遇到了异常无法获取未定义或空引用的属性'forEach'请帮我,我在哪里做错了

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

2 个答案:

答案 0 :(得分:3)

您必须为此创建一个自定义管道,就像我在这里所做的:

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

HTML:

  volumes:
    - name: data-storage
      persistentVolumeClaim:
        claimName: main-dev-pvc-${node.failure-domain.beta.kubernetes.io/zone}

我已经在此处实现了解决方案:https://stackblitz.com/edit/angular-ldhmnk

希望有帮助。

答案 1 :(得分:0)

您好,默认情况下您没有该管道,但是您可以在http://www.competa.com/blog/custom-groupby-pipe-angular-4/

中找到类似的内容