You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML层面对ngFor遍历数据去重 无需改动组件逻辑

Angular ngFor 仅在HTML层面去重的实现方案

因为Angular没有内置去重管道,我们可以先创建一个全局通用的纯管道(不属于业务组件代码,无需修改你当前的组件逻辑),之后直接在HTML模板中调用即可:

步骤1:创建全局去重管道

新建unique.pipe.ts文件,代码如下:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'unique',
  pure: true
})
export class UniquePipe implements PipeTransform {
  transform(arr: any[], deduplicateKey: string): any[] {
    if (!Array.isArray(arr) || !deduplicateKey) return arr;
    const seen = new Set();
    return arr.filter(item => {
      const keyValue = item[deduplicateKey];
      if (!seen.has(keyValue)) {
        seen.add(keyValue);
        return true;
      }
      return false;
    });
  }
}

将该管道添加到对应模块的declarations数组中完成注册,后续所有组件的模板都可以直接使用这个管道。

步骤2:修改HTML模板

直接在ngFor的数据源后调用unique管道,传入去重的依据字段type即可:

<mat-option *ngFor="let primer of dataService.data | unique:'type'" [value]="primer.type" id="primer">{{primer.type}}</mat-option>

注意事项

  • 纯管道只会在输入的数据源引用发生变化时重新计算,性能优于在组件中每次渲染都处理数组
  • 如果你的数据源是基础类型数组(如字符串、数字数组),可以调整管道逻辑省略key参数,直接对数组项本身去重

内容的提问来源于stack exchange,提问作者David Cibin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:09:00