使用* ngFor在Angular材质中分组对象数组

问题描述 投票:0回答:1

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'"抛出错误,我找不到任何文档。

javascript angular loops group-by
1个回答
2
投票

你应该制作自己的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

© www.soinside.com 2019 - 2024. All rights reserved.