代码之家  ›  专栏  ›  技术社区  ›  CGFoX

使用*ngFor对角度材质中的对象数组进行分组

  •  0
  • CGFoX  · 技术社区  · 6 年前

    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 answer 使用 ng-repeat 用一个 groupBy 我想要多个扩展面板,每个团队一个,当扩展时,显示参与的玩家。

    <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重复 不允许进入 mat-expansion-panel *ngFor 是允许的,但我不知道怎么和 过滤器。 *ngFor="let player in players | groupBy: 'team'"

    1 回复  |  直到 6 年前
        1
  •  4
  •   Sajeetharan    6 年前

    你应该自己做 custom pipe 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