this related question类似,我想对对象数组e.g., by team name进行分组

[
 {name: 'Gene', team: 'team alpha'},
 {name: 'George', team: 'team beta'},
 {name: 'Steve', team: 'team gamma'},
 {name: 'Paula', team: 'team beta'},
 {name: 'Scruath of the 5th sector', team: 'team gamma'}
];


不幸的是,accepted answerng-repeat过滤器一起使用groupBy似乎在Angular Material扩展面板中不起作用,这是我要尝试的操作:
我想要多个扩展面板,每个团队一个,当扩展时会显示参与的玩家。

我试过了

<mat-expansion-panel ng-repeat="(key, value) in players | groupBy: 'team'">
    <mat-expansion-panel-header>
      <mat-panel-title>{{ key }}</mat-panel-title>
    </mat-expansion-panel-header>
    <li ng-repeat="player in value">
      {{player.name}}
    </li>
</mat-expansion-panel>


但是,ng-repeat内不允许使用mat-expansion-panel。允许使用*ngFor,但我不知道如何将其与groupBy过滤器一起使用。 *ngFor="let player in players | groupBy: 'team'"引发错误,我找不到任何文档。

最佳答案

您应该制作自己的custom pipe以支持GroupBy,而且ng-repeat是angularjs语法,您应该使用ngFor

您的自定义管道应如下所示:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
    transform(collection: Array<any>, property: string): Array<any> {
         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] }));
    }
}


STACKBLITZ DEMO

关于javascript - 用* ngFor对Angular Material中的对象数组进行分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52139874/

10-12 15:32