How to do group-By using custom pipes in angular

可紊 提交于 2019-12-13 03:46:15

问题


I am trying to group by my list of an array by date using below code but it's not working and just showing group by date but not showing related child data I do not understand where did I do a mistake and I am a learner and I follow http://www.competa.com/blog/custom-groupby-pipe-angular-4/ link for doing my requirement

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

来源:https://stackoverflow.com/questions/51263483/how-to-do-group-by-using-custom-pipes-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!