我有一组json格式化字符串,需要使用日期过滤数据。它类似于使用angular2过滤所有日期,最近3个月和过去6个月
请找到以下结构,我需要使用日期过滤数据。
<ul>
<li*ngFor="let account of activities">
{{accont.activityDate | date}} - {{account.activityDescription}}
</li>
</ul>
我的Json数据是:
"activities": [
{
"activityDate": "2016-07-02",
"activityDescription": "Data1",
},
{
"activityDate": "2016-08-23",
"activityDescription": "Data2",
},
{
"activityDate": "2016-04-11",
"activityDescription": "Data3",
}
{
"activityDate": "2016-04-11",
"activityDescription": "Data4",
}
{
"activityDate": "2015-07-21",
"activityDescription": "Data5",
}
];
"activities": [{
"activityDate": "2016-07-02",
"activityDescription": "Data1",
}, {
"activityDate": "2016-08-23",
"activityDescription": "Data2",
}, {
"activityDate": "2016-04-11",
"activityDescription": "Data3",
} {
"activityDate": "2016-04-11",
"activityDescription": "Data4",
} {
"activityDate": "2015-07-21",
"activityDescription": "Data5",
}];
<ul>
<li *ngFor="let account of activities">
{{accont.activityDate | date}} - {{account.activityDescription}}
</li>
</ul>
答案 0 :(得分:1)
日期管道可以帮助您格式化日期,而不是过滤它。
您应该根据您的条件传递一组已过滤的活动。 写一些类似的东西:
<ul>
<li*ngFor="let account of filteredActivities">
{{accont.activityDate | date}} - {{account.activityDescription}}
</li>
</ul>
并在您的组件中
private filteredActivities;
private dateLimit = new Date().getTime() - (30 * 24 * 60 * 60 * 1000); // 30 days ago ... define as and where you wish
filterActivities() {
return this.activities.filter(activity => {
let date:Date = new Date(activity.activityDate);
return date.getTime() > dateLimitInMS;
});
}
你可以调用ngInit中的filteredActivities和更改dateLimit。
不要编写自定义管道,也不要传递filteredActivities函数本身,有角度的团队解释了为什么 https://angular.io/docs/ts/latest/guide/pipes.html#!#no-filter-pipe
编辑:这里有一个选项,你有一个限制列表和一个事件在你选择的东西时触发..使用此事件来设置filteredActivities的新值。
<select (change)="onLimitChange($event)">
<option *ngFor="let limit of limits" [value]="limit.value">
{{limit.name}}
</option>
</select>