我的角度应用程序中有这个数组
calendarDates = [
{"date": "2018-10-23", "day": 23, "month":10, "year":2018, "price":"2313", "date_is_valid": true},
{"date": "2018-10-24", "day": 24, "month":10, "year":2018, "price":"2313", "date_is_valid": true},
...
{"date": "2018-11-01", "day": 1, "month":11, "year":2018, "price":"2313", "date_is_valid": false},
...
{"date": "2019-02-01", "day": 1, "month":12, "year":2019, "price":"2313", "date_is_valid": true}
]
我的目标是使用相同的数组在html中使用此结构:
<div *ngFor='let calendarDate of calendarDates'>
<div class='month'>
<div class='october'>
<p>{{getMonthName}}</p>
<div class='date'>{{calendarDate.date}} (2018-10-23)</div>
<div class='date'>{{calendarDate.date}} (2018-10-24)</div>
...
</div>
<div class='november'>
<p>{{getMonthName}}</p>
<div class='date'>{{calendarDate.date}} (2018-11-01)</div>
...
</div>
<div class='february'>
<p>{{getMonthName}}</p>
<div class='date'>{{calendarDate.date}} (2019-02-01)</div>
...
</div>
</div>
</div>
我不知道该如何过滤,最好的方法是在html本身中按月对日期进行分类并将日期包装到month div。
如何在ngIf中创建月份包装器?然后,这些值可以在交互期间更改,例如price或date_is_valid,因此它必须是相同的来源。
答案 0 :(得分:2)
您可以通过创建一个管道进行分类来进行。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
transform(collection: Array, property: string): Array {
if(!collection) {
return null;
}
const groupedCollection = collection.reduce((previous, current)=> {
if(!previous[current[property]]) {
previous[current[property]] = [current];
} else {
previous[current[property]].push(current);
}
return previous;
}, {});
return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
}
}
<div *ngFor='let calendarDatesByMonth of calendarDates | groupBy:'month''>
<div class='month >
<div class='october'>
<p>{{getMonthName(calendarDatesByMonth.key)}}</p> <!-- calendarDatesByMonth.key is month number -->
<div *ngFor='let calendarDate of calendarDatesByMonth.value' class='date'>{{calendarDate.date}} (2018-10-23)</div>
</div>
</div>
</div>