
本教程详细指导如何在angular应用中为数据列表实现多字段模糊搜索功能。我们将从现有单字段过滤逻辑出发,逐步优化为支持姓名、邮箱、用户名等多个字段的灵活查询。教程将深入探讨如何利用javascript的数组和字符串方法进行高效过滤,并介绍如何有效管理原始数据与过滤结果,确保搜索体验流畅且高效。
在Web应用中,数据列表的过滤是一个常见需求。用户通常希望通过输入关键词来快速查找相关信息。实现这一功能的核心在于以下几个JavaScript数组和字符串方法:
原始代码展示了一个基于mat-table的用户列表,并实现了一个简单的单字段(lastName)过滤功能。
原始HTML片段:
<input type="text" [(ngModel)]="lastname" (input)="Search()"/>
<mat-table [dataSource]="usuarios">
<!-- ... 省略其他列定义 ... -->
<ng-container matColumnDef="firstName">
<mat-header-cell *matHeaderCellDef> Nome </mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.firstName }}</mat-cell>
</ng-container>
<ng-container matColumnDef="lastName">
<mat-header-cell *matHeaderCellDef>Sobrenome</mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.lastName }}</mat-cell>
</ng-container>
<ng-container matColumnDef="username">
<mat-header-cell *matHeaderCellDef>Username</mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.username }}</mat-cell>
</ng-container>
<ng-container matColumnDef="email">
<mat-header-cell *matHeaderCellDef>E-mail</mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.email }}</mat-cell>
</ng-container>
<!-- ... 其他列和操作按钮 ... -->
</mat-table>原始TypeScript片段:
export class GerenciamentoUsuariosListaComponent implements OnInit {
@Input() usuarios: any[] = []; // 显示的数据源
usuarios1: any; // 似乎用于临时存储,但未充分利用
lastname :string; // 搜索关键词,仅用于姓氏
readonly displayedColumns = ['firstName', 'lastName', 'username','email','actions'];
constructor(private service: GerenciamentoUsuariosService) {
this.lastname = '';
}
ngOnInit(): void {
this.refreshListUser1()
}
refreshListUser1() {
this.usuarios1 = this.service.list().subscribe(
resp => {
this.usuarios = resp.content // 直接赋值给显示数据源
console.log(this.usuarios)
});
}
Search(){
if(this.lastname != ""){
this.usuarios = this.usuarios.filter(res =>{
return res.lastName.toLocaleLowerCase().match(this.lastname.toLocaleLowerCase());
})
}else if(this.lastname == ""){
this.ngOnInit(); // 问题:清空搜索词时会重新加载数据
}
}
}现有实现存在以下优化点:
我们将对上述代码进行改进,以实现高效的多字段模糊搜索。
首先,我们将搜索输入框的 [(ngModel)] 绑定到一个更通用的变量 searchTerm。
<input type="text" [(ngModel)]="searchTerm" (input)="Search()" placeholder="搜索姓名、邮箱或用户名"/>
<mat-table [dataSource]="usuarios">
<!-- Name Column -->
<ng-container matColumnDef="firstName">
<mat-header-cell *matHeaderCellDef> 姓名 </mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.firstName }}</mat-cell>
</ng-container>
<!-- Last Name Column -->
<ng-container matColumnDef="lastName">
<mat-header-cell *matHeaderCellDef>姓氏</mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.lastName }}</mat-cell>
</ng-container>
<!-- UserName Column -->
<ng-container matColumnDef="username">
<mat-header-cell *matHeaderCellDef>用户名</mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.username }}</mat-cell>
</ng-container>
<!-- Email Column -->
<ng-container matColumnDef="email">
<mat-header-cell *matHeaderCellDef>电子邮件</mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.email }}</mat-cell>
</ng-container>
<!-- ... 其他列和操作按钮 ... -->
</mat-table>在组件中,我们将引入一个新数组 originalUsuarios 来存储从后端获取的完整用户列表。usuarios 数组将始终用于显示过滤后的结果。
import { Component, OnInit, Input } from '@angular/core';
import { GerenciamentoUsuariosService } from './gerenciamento-usuarios.service'; // 假设服务路径正确
@Component({
selector: 'app-gerenciamento-usuarios-lista',
templateUrl: './gerenciamento-usuarios-lista.component.html',
styleUrls: ['./gerenciamento-usuarios-lista.component.scss']
})
export class GerenciamentoUsuariosListaComponent implements OnInit {
@Input() usuarios: any[] = []; // 用于显示和过滤的数据列表
originalUsuarios: any[] = []; // 存储原始的完整数据列表
searchTerm: string = ''; // 通用的搜索关键词
readonly displayedColumns = ['firstName', 'lastName', 'username', 'email', 'actions'];
constructor(private service: GerenciamentoUsuariosService) { }
ngOnInit(): void {
this.refreshListUser1();
}
refreshListUser1(): void {
this.service.list().subscribe(
resp => {
this.originalUsuarios = resp.content; // 将完整数据存储到 originalUsuarios
this.usuarios = [...this.originalUsuarios]; // 初始化显示列表为完整数据
console.log(this.usuarios);
},
error => {
console.error('获取用户列表失败:', error);
// 处理错误,例如显示错误消息给用户
}
);
}
Search(): void {
const keyword = this.searchTerm.toLocaleLowerCase().trim(); // 获取并转换为小写,去除首尾空格
if (keyword) {
// 如果有搜索关键词,则从原始数据中过滤
this.usuarios = this.originalUsuarios.filter(res => {
return res.firstName.toLocaleLowerCase().includes(keyword) ||
res.lastName.toLocaleLowerCase().includes(keyword) ||
res.username.toLocaleLowerCase().includes(keyword) ||
res.email.toLocaleLowerCase().includes(keyword);
});
} else {
// 如果搜索关键词为空,则重置显示列表为原始完整数据
this.usuarios = [...this.originalUsuarios];
}
}
}代码解释:
PbootCMS是一款高效、简洁、强悍的开源PHP企业网站开发建设管理系统。 PbootCMS 1.1.8 更新日志:2018-08-07 1.修复提交表单多选字段接收数据问题; 2.修复登录过程中二次登陆在页面不刷新时验证失败问题; 3.新增搜索结果fuzzy参数来控制是否模糊匹配; 4.新增父分类,顶级分类名称及链接独立标签,具体见手册; 5.新增内容多图拖动排序功能。
243
性能优化 (去抖/Debounce): 对于包含大量数据或用户输入非常频繁的场景,input 事件可能触发 Search() 方法过于频繁。可以考虑使用 RxJS 的 debounceTime 操作符来延迟 Search() 方法的执行,例如:
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
export class GerenciamentoUsuariosListaComponent implements OnInit, OnDestroy {
// ... 其他变量 ...
private searchTerms = new Subject<string>();
private destroy$ = new Subject<void>(); // 用于管理订阅的生命周期
constructor(private service: GerenciamentoUsuariosService) { }
ngOnInit(): void {
this.refreshListUser1();
this.searchTerms.pipe(
debounceTime(300), // 300毫秒内没有新输入则执行
takeUntil(this.destroy$) // 组件销毁时取消订阅
).subscribe(() => {
this.Search();
});
}
// 在HTML中调用这个方法
onSearchInput(): void {
this.searchTerms.next(this.searchTerm);
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
// ... Search() 方法保持不变 ...
}HTML中将 (input)="Search()" 改为 (input)="onSearchInput()"。
可扩展性: 如果需要过滤的字段非常多,或者过滤条件需要动态配置,可以考虑将过滤逻辑抽象成一个独立的函数或服务,甚至使用第三方库(如 lodash 的 filter 或自定义管道 Pipe)。
后端过滤: 对于非常大的数据集(例如数万条甚至更多),前端进行过滤可能会导致性能瓶颈。在这种情况下,更推荐将过滤逻辑推送到后端API实现,前端只负责发送搜索关键词并接收过滤后的数据。
用户体验: 考虑在数据加载或过滤时显示加载指示器(如 mat-spinner),并在没有搜索结果时显示友好的提示信息。
完全匹配 vs. 模糊匹配: 当前实现是模糊匹配 (includes())。如果需要完全匹配,可以将 includes(keyword) 替换为 === keyword。
通过本教程,我们学习了如何在Angular项目中实现一个健壮且高效的多字段模糊搜索功能。关键在于:
掌握这些技巧,您将能够为您的Angular应用构建出更加强大和用户友好的数据列表过滤功能。
以上就是在Angular项目中实现高效多字段模糊搜索与数据过滤的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号