如何通过在角度中使用自定义管道进行分组

时间:2018-07-10 10:58:40

标签: angular group-by ionic3 angular-pipe

我正在尝试使用以下代码按日期对数组列表进行分组,但它不起作用,仅按日期进行分组,但未显示相关的子数据,我不知道我在哪里做错了,我是一个学习者并且我点击http://www.competa.com/blog/custom-groupby-pipe-angular-4/链接来满足我的要求

home.ts:

  events: any;

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {

    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 | groupByCategory:'date' ">
    <ion-item-divider color="light">
        {{ group.date}}
    </ion-item-divider>
    <ion-item>{{ group.title}}</ion-item>
</ion-item-group>
</ion-content>

groupByCategory:

 @Pipe({ name: 'groupByCategory' })
export class GroupbycategoryProvider implements PipeTransform {

  transform(collection: Array<any>, property: string= 'date'): Array<any> {
    // prevents the application from breaking if the array of objects doesn't exist yet
    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;
    }, {});
    // this will return an array of objects, each object containing a group of objects
    return Object.keys(groupedCollection).map(date=> ({ date, events: groupedCollection[date] }));
  }
}

0 个答案:

没有答案