Angular自定义groupBy管道分组时报TS2345类型错误如何解决?
问题解决方法
1. 解决TS类型报错
报错原因:模板中使用了可选链d?.items,当d为空或items字段不存在时,值为undefined,但你的groupBy管道入参仅声明了接受any[]类型,不兼容undefined所以触发类型校验错误。
可任选一种方法解决:
- 方法1:修改管道入参类型兼容undefined,同时将空值返回值从null改为空数组,避免
*ngFor循环空值报错:
@Pipe({ name: 'groupBy' }) export class GroupByPipe implements PipeTransform { // 入参增加undefined类型支持 transform(collection: any[] | undefined, property: string): any[] { if (!collection) { return []; // 空值返回空数组 } 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] })); } }
- 方法2:模板中给
d?.items增加默认空数组兜底:
*ngFor="let group of (d?.items ?? []) | groupBy: 'category'"
2. 解决分组展示异常问题
异常原因:你的groupBy管道返回的结构为[{key: '分类名', value: [该分类下所有条目数组]}, ...],但原模板没有对分组内的value数组做二次循环,还错误地直接取分组对象的category字段(分组对象仅包含key和value两个字段,无category字段),导致分组展示错误。
修改后的模板代码:
<ng-container *ngFor="let d of data; index as i"> {{d.name}} <!-- 第一层循环所有分类组 --> <ng-container *ngFor="let group of (d?.items ?? []) | groupBy: 'category'; index as j"> <!-- 渲染分类头 --> <div class="label-view"> {{group.key}} </div> <!-- 第二层循环当前分类下的所有条目 --> <ng-container *ngFor="let item of group.value"> <div class="label-view"> {{item.itemNumber}} </div> </ng-container> </ng-container> </ng-container>
补充注意事项
如果你的items数组是动态更新的(后续会新增/删除/修改条目),需要把管道设置为非纯管道,否则Angular不会自动触发管道重新计算分组:
@Pipe({ name: 'groupBy', pure: false // 新增该配置 })
内容的提问来源于stack exchange,提问作者lona bin
相关产品推荐
相关产品推荐

