angular - 如何按日期对列表进行分组
问题描述
我正在尝试使用下面的代码按日期显示列表,但出现异常无法获取未定义或空引用的属性“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'
}]
}
主页.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>
分组日期:
@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] }));
}
}
解决方案
您必须为此创建一个自定义管道,就像我在这里所做的那样:
@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>
我在这里实现了解决方案:https ://stackblitz.com/edit/angular-ldhmnk
希望能帮助到你。
推荐阅读
- batch-file - Windows 批处理脚本将最新文件从 Windows 的特定目录传输到每 30 分钟运行一次的 Linux 服务器
- google-colaboratory - 为什么 Google colab 会说:chmod: cannot access 'RDP.sh': No such file or directory
- python - 使用 Beautiful Soup 在网站中使用两个表进行 Web 抓取
- sql - 如何在 ibm db2 中执行事务
- math - 关于SVD,奇异值分解的问题
- java - Appium:appium无法识别chromeOptions
- asp.net-mvc - 如何在 ASP.NET mvc 上使用 npm 安装包
- python - 使用 BeautifulSoup获取标签时遇到问题
- java - 使用 Chronicle 进行单元测试
- php - 使用 DOMDocument PHP 进行抓取