angular - 在多个字段上搜索管道以查找一组项目
问题描述
我有一个管道用于搜索一组用户的 ID 或名称。它工作正常。如果我写下用户 ID 号,它会找到它。如果我写名字,它只会在名字按顺序写的情况下找到
但我想搜索名字和姓氏的例子,并得到名字为第二个名字的用户,第三个名字为姓氏
我知道我必须拆分查询字符串( splitted = querystring.split(' ') 并搜索这两个名称,但我不知道如何。
我不想要 2 个术语的静态搜索,而是 2、3 等的动态搜索……用户想要的那些。
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({
name: 'querystring'
})
@Injectable()
export class PesquisaPipe implements PipeTransform {
transform(users: any[], querystring: any): any[] {
if ( querystring=== undefined) {
return users;
}
return users.filter(z => {
const userID = z.userID.toString().includes(querystring.toLocaleLowerCase());
const userName = z.userName.toLocaleLowerCase().includes(querystring.toLocaleLowerCase());
return( userID + userName);
});
}
解决方案
欢迎来到堆栈溢出!
首先,使用管道进行过滤或排序是个坏主意。文档在这里对此提出警告:https ://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
相反,在代码中进行过滤。
其次,有几种方法可以处理多个案例的过滤,我在这里有一篇博客文章:https ://blogs.msmvps.com/deborahk/filtering-in-angular/
通常,您可以使用 OR || 过滤多个条件。如下:
performFilter(filterBy: string): IProduct[] {
filterBy = filterBy.toLocaleLowerCase();
return this.products.filter((product: IProduct) =>
product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1 ||
product.description.toLocaleLowerCase().indexOf(filterBy) !== -1);
}
如果在productName
OR中找到,上面的代码会归档一个指定的字符串description
。
或者您可以过滤任何对象属性,如下所示:
performFilter(filterBy: string): IProduct[] {
filterBy = filterBy.toLocaleLowerCase();
return this.products.filter((product: IProduct) =>
Object.keys(product).some(prop => {
let value = product[prop];
if (typeof value === "string") {
value = value.toLocaleLowerCase();
}
return value.toString().indexOf(filterBy) !== -1;
})
);
}
上面的代码在对象的所有属性中搜索特定提供的字符串。
链接的博客文章提供了其他选项。
将此应用于我认为您要问的问题:
performFilter(filterBy: string): User[] {
filterBy = filterBy.toLocaleLowerCase();
return this.users.filter((user: User) =>
user.name.toLocaleLowerCase().indexOf(filterBy) !== -1 ||
user.userId.toLocaleLowerCase().indexOf(filterBy) !== -1 ||
user.userName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}
推荐阅读
- javascript - 未捕获的错误:语法错误,无法识别的表达式:input[name=ms_harga[]]
- python - 加入由主键链接的 2 个 JSON 输入
- sql - sql server中带有空句柄的案例运算符
- css - 我需要使用哪个 css 单元,这样所有分辨率的页面都不会滚动(基本笔记本电脑分辨率和 1920X1080 FHD 分辨率))
- javascript - 使用 moment.js 将天数转换为月数和剩余天数
- javascript - OpenLayers 地图上的可拖动图标
- sql - 从oracle中的日期列获取日期和时间
- android - 从屏幕上绘制图像但仍然从屏幕上获得点击事件
- mongodb - MongoDB | 使用数组进行图形查找
- php - 在 httpd 服务的 php 应用程序上启用 HTTPS