【问题标题】:Unable to do searching using custom pipe created in angular 7无法使用在 Angular 7 中创建的自定义管道进行搜索
【发布时间】:2019-08-02 07:13:13
【问题描述】:

如何使用管道在角度 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 应该是 indexOf

标签: javascript arrays angular search


【解决方案1】:

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

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

Angular 不提供这样的管道,因为它们的性能很差并且会阻止激进的缩小。 filter 和 orderBy 都需要引用对象属性的参数。阅读更多关于 here 的信息。

话虽如此,您基本上可以在组件内部编写过滤数据的逻辑:

来,试试看:

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)
    ];
  }
}

这里有一个Working CodeSandbox Sample 供您参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多