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

Angular项目用户列表多字段过滤功能实现求助

实现多字段用户列表过滤

问题分析

你当前的过滤逻辑仅针对姓氏(lastName)字段,要扩展到名字、用户名、邮箱,需要调整两个关键点:

  1. 保留原始用户数据集,避免过滤后丢失原数据
  2. 修改过滤逻辑,同时匹配多个目标字段

修改方案

1. 调整HTML代码

把输入框的绑定变量从lastname改为更通用的searchTerm,语义更清晰:

<input type="text" [(ngModel)]="searchTerm" (input)="Search()"/>
<mat-table [dataSource]="usuarios">
    <!-- 原有列定义保持不变 -->
    ...
</mat-table>

2. 更新Component.ts代码

  • 添加originalUsuarios变量存储原始用户数据,避免过滤时覆盖原数组
  • 修改Search方法,同时匹配firstName、lastName、username、email四个字段
  • 优化空搜索词的处理逻辑,直接复用本地原始数据,无需重新请求接口
export class GerenciamentoUsuariosListaComponent implements OnInit {
  @Input() usuarios: any[] = [];
  // 新增:存储原始用户数据,用于过滤重置
  originalUsuarios: any[] = [];
  usuarios1: any;
  // 把变量名改为通用的searchTerm
  searchTerm: string = '';

  readonly displayedColumns = ['firstName', 'lastName', 'username','email','actions'];

  constructor(private service: GerenciamentoUsuariosService) {}

  ngOnInit(): void {
    this.refreshListUser1()
  }

  refreshListUser1() {
    this.usuarios1 = this.service.list().subscribe(
      resp => {
        // 同时给原始数组和展示数组赋值
        this.originalUsuarios = resp.content;
        this.usuarios = resp.content;
        console.log(this.usuarios)
      });
  }

  Search(){
    if(this.searchTerm.trim() !== ""){
      const lowerCaseTerm = this.searchTerm.toLocaleLowerCase();
      // 过滤时检查多个字段,只要任意一个匹配就保留
      this.usuarios = this.originalUsuarios.filter(user =>{
        return user.firstName.toLocaleLowerCase().includes(lowerCaseTerm)
            || user.lastName.toLocaleLowerCase().includes(lowerCaseTerm)
            || user.username.toLocaleLowerCase().includes(lowerCaseTerm)
            || user.email.toLocaleLowerCase().includes(lowerCaseTerm);
      })
    }else{
      // 搜索词为空时,直接恢复原始数据
      this.usuarios = [...this.originalUsuarios];
    }
  }
}

关键优化点说明

  • 使用includes()替代match(),更适合简单的包含匹配(match()通常用于正则,这里没必要)
  • 提前将搜索词转为小写,避免重复计算
  • 用扩展运算符[...this.originalUsuarios]创建数组副本,防止直接引用导致的原数组意外修改
  • 移除ngOnInit()的调用,改用本地原始数据重置,提升性能并避免不必要的接口请求

内容的提问来源于stack exchange,提问作者Jeferson Carlos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:13:01