如何在Angular下拉框选项中去除重复数据?
Angular下拉框*ngFor去重方案
方法一:组件内预处理数据(推荐)
在组件初始化阶段对UserTypes数组做去重处理,避免模板中混入业务逻辑,提升性能与可维护性。
组件代码
// 组件类内部 uniqueUserTypes: Array<{id: any, name: string}>; ngOnInit(): void { // 根据id字段去重,如需按name去重替换为item.name即可 this.uniqueUserTypes = Array.from( new Map(this.UserTypes.map(item => [item.id, item])).values() ); }
模板修改
将原*ngFor遍历的数组替换为去重后的uniqueUserTypes:
<option *ngFor="let type of uniqueUserTypes; let i = index" [ngValue]="type.id"> <span>{{type.name}}</span> </option>
方法二:自定义去重管道(适合多场景复用)
如果需要在多个组件的下拉框中复用去重逻辑,可创建自定义管道。
创建UniquePipe
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'unique' }) export class UniquePipe implements PipeTransform { transform(value: Array<any>, uniqueKey: string): Array<any> { if (!value || !uniqueKey) return value; // 利用Map键的唯一性过滤重复项 return Array.from( new Map(value.map(item => [item[uniqueKey], item])).values() ); } }
需在对应模块的declarations数组中声明该管道。
模板使用
在*ngFor中添加管道并指定去重字段(如id):
<option *ngFor="let type of UserTypes | unique: 'id'; let i = index" [ngValue]="type.id"> <span>{{type.name}}</span> </option>
内容的提问来源于stack exchange,提问作者vince
相关产品推荐
相关产品推荐

