首页 > 解决方案 > 无法使用在 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 进行包含搜索?

标签: javascriptarraysangularsearch

解决方案


您应该使用indexOf代替===or indexof(我认为这是您的代码中的错字)。

另外,您不应该使用 apipe来过滤值。这就是为什么 Angular 不建议使用pipes 来过滤或排序值。

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 示例


推荐阅读