如何在Angular 6+中复制AngularJS中的groupBy过滤器



我正在将一些旧的AngularJS网站/应用程序更新到Angular的新版本,并有一个关于如何替换旧的groupBy过滤器的问题。

<li ng-repeat="(key, value) in attendees | groupBy: 'location'">
<div class="item-title">{{ key }}</div>
<div ng-repeat="attendee in value"><p>{{ attendee.name }}<span ng-if="attendee.description != ''">{{ attendee.description }}</span></p></div>
</li>

以下是与会者数据的实物模型:

[{
"id": 1,
"location": "United States",
"name": "Walter Johnson",
"description": ""
}, {
"id": 2,
"location": "Canada",
"name": "Jerry Lewis",
"description": ""
}, {
"id": 3,
"location": "Canada",
"name": "Missy Mayer",
"description": "5 Years"
}, {
"id": 4,
"location": "United States",
"name": "Marvin Moore",
"description": ""
}, {
"id": 5,
"location": "United States",
"name": "Nelson Cooper",
"description": ""
}]

我是否仍然可以从与会者数据中为每个唯一的位置项目创建项目标题?

感谢提供任何信息或指导。

angular团队建议避免使用会改变数据的管道,这就是为什么像filter、orderBy和groupBy这样的管道没有内置到angular 2+中的原因。相反,只需将控制器中的数据分组即可。以下是它的样子:

控制器:

export class AppComponent {
name = "Angular " + VERSION.major;
data = [
{
id: 1,
location: "United States",
name: "Walter Johnson",
description: ""
},
{
id: 2,
location: "Canada",
name: "Jerry Lewis",
description: ""
},
{
id: 3,
location: "Canada",
name: "Missy Mayer",
description: "5 Years"
},
{
id: 4,
location: "United States",
name: "Marvin Moore",
description: ""
},
{
id: 5,
location: "United States",
name: "Nelson Cooper",
description: ""
}
];
groups = {};
ngOnInit() {
this.groups = this.data.reduce((acc, curr) => {
if (!acc[curr.location]) {
acc[curr.location] = [];
}
acc[curr.location].push(curr);
return acc;
}, {});
}
}

然后在模板中,可以将KeyValueMap与*ngFor结合使用。KeyValuePipe将对Array.prototype.reduce()*ngFor生成的对象中的每个键或"组"进行迭代,以对组数组中的每个项进行迭代:

<ul>
<li *ngFor="let item of groups | keyvalue">
<div>location: {{item.key}}</div>
<div>
<div *ngFor="let location of item.value">{{location | json}}</div>
</div>
<li>
</ul>

请注意,有些库公开了筛选、分组和排序管道,但这个答案是从管道文档中提供的建议中得出的。

如果需要更新groups的值,只需在需要时再次执行reduce函数。

希望这能有所帮助!

最新更新