Javascript 使用*ngFor将角度材质中的对象数组分组
类似于,我想对一组对象进行分组,Javascript 使用*ngFor将角度材质中的对象数组分组,javascript,angular,loops,group-by,Javascript,Angular,Loops,Group By,类似于,我想对一组对象进行分组,例如,按团队名称进行分组 [ {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'} ]; 不幸的是,将ng
例如,按团队名称进行分组
[
{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'}
];
不幸的是,将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>
{{key}}
{{player.name}
但是,
ng repeat
不允许在mat扩展面板内进行<允许使用code>*ngFor
,但我不知道如何将其与groupBy
过滤器一起使用*ngFor=“let player in players | groupBy:'team'
抛出错误,我找不到任何文档。您应该制作自己的自定义管道来支持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] }));
}
}
从'@angular/core'导入{Pipe,PipeTransform};
@管道({name:'groupBy'})
导出类GroupByPipe实现PipeTransform{
transform(集合:Array您应该制作自己的自定义管道
以支持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] }));
}
}
从'@angular/core'导入{Pipe,PipeTransform};
@管道({name:'groupBy'})
导出类GroupByPipe实现PipeTransform{
transform(collection:Array您可以使用您可以使用为什么他们要从AngularJS中删除功能?我希望许多人可以从内置的“groupBy”管道中受益。后续问题:如果我尝试按日期分组,但不是按确切日期(随时间)分组,会怎么样真的只有一年、一个月、一天?我试着链接管道,但没用。我可能不得不在之前减少小时、分钟、秒、毫秒,对吧?为什么他们要从AngularJS中删除功能?我想很多人都可以从内置的“groupBy”中受益管道。后续问题:如果我试图按日期分组,但不按确切日期(含时间)只按年、月、日分组,该怎么办?我尝试链接管道,但没有效果。我可能必须在之前减少小时、分钟、秒、毫秒,对吗?