javascript - 无法使用在 Angular 7 中创建的自定义管道进行搜索
问题描述
如何使用管道在角度 7 中搜索(如角度 1 中的过滤器)?下面是我试过的代码。但只有在完全匹配的情况下才会返回。但我需要包含该词的结果。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'search',
pure:true
})
export class SearchPipe implements PipeTransform {
transform(data: any,searchTxt:string): any {
if(!data || !searchTxt)
{
return data;
}
return data.filter(function(x) {
return x.name ==searchTxt}) ;
}`
}
我也尝试了下面的代码但不起作用
return data.filter(x=>x.name.toString().toLowerCase().indexof(searchTxt.toLowerCase()) !== -1)
这会引发错误:x.name.indexof 不是函数
如何使用 javascript\angular 进行包含搜索?
解决方案
您应该使用indexOf
代替===
or indexof
(我认为这是您的代码中的错字)。
另外,您不应该使用 apipe
来过滤值。这就是为什么 Angular 不建议使用pipe
s 来过滤或排序值。
Angular 不提供这样的管道,因为它们的性能很差并且会阻止激进的缩小。filter 和 orderBy 都需要引用对象属性的参数。在此处阅读更多相关信息。
话虽如此,您基本上可以在组件内部编写过滤数据的逻辑:
在这里,试一试:
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
users = [];
filteredUsers = [];
constructor(private http: HttpClient) {}
ngOnInit() {
this.http
.get("https://jsonplaceholder.typicode.com/users")
.subscribe((users: any[]) => {
this.users = users;
this.filteredUsers = [...this.users];
});
}
onSearchTextChange(searchString) {
this.filteredUsers = [
...this.users.filter(user => user.name.indexOf(searchString) > -1)
];
}
}
这是您的参考的工作 CodeSandbox 示例。
推荐阅读
- python - 如何计算 numpy64float 类型的数组的平均值?
- angular - Angular网站移动浏览器页面速度
- google-chrome-extension - Chrome 扩展程序 | 多个警报同时响起
- angle - 如何翻转一个角度
- sql - 如何查询具有不同键值对的嵌套 json
- php - 格式化以 + 或 - 开头的时区偏移量
- javascript - (Sweetalert2 Toast) 如何禁用 ENTER/SPACE、ESC 和单击框外?
- postman - 如何将此 http POST 请求输入 Postman?
- r - 使用 ggplot2 绘制数据框的行
- elasticsearch - 如何计算弹性搜索中大于平均值的最小值?