【问题标题】:Using a custom pipe as a search filter on a table使用自定义管道作为表上的搜索过滤器
【发布时间】:2019-03-25 17:07:52
【问题描述】:

所以我有这张表,里面有数据。现在我想实现一个搜索栏,在搜索后过滤表格。为此,我假设我需要使用管道来过滤搜索。但是,这对我不起作用,我不知道这怎么可能。

表中的数据来自assets下本地存储的json文件。该表写在 app.compinent.html 文件中。

我已经创建了一个管道,但我不知道它里面的代码应该是什么。

这是我正在尝试完成的一个示例,但是数据位于一个表中,该表从本地存储的文件中获取数据。

https://stackblitz.com/edit/angular-5ujgcy

我的代码:

import { Pipe, PipeTransform } from '@angular/core';


@Pipe({
  name: 'countrysearch'
})


export class CountrysearchPipe implements PipeTransform {
  transform(Country: any[], searchText: string): any[] {
    if(!Country) return [];
    if(!searchText) return Country;
searchText = searchText.toLowerCase();
return Country.filter( it => {
      return it.toLowerCase().includes(searchText);
    });
   }
}

//html

<input [(ngModel)]="searchText" placeholder="search text goes here">
    <ul>
        <li *ngFor="let country of Countries | filter : searchText">
        {{countries.Name}}
        </li>
    </ul>


    <table border="1">
        <!-- ADD HEADERS -->
        <tr>
            <th>>Name</th>
            <th>People</th>

<tr *ngFor="let country of Countries ">
            <td>{{ country.Name }}</td>
            <td>{{ country.People }}</td>
</tr>
</table>

【问题讨论】:

  • 那是什么问题?
  • 它不起作用我不确定出了什么问题,我得到了 0 个结果。当我从表中获取数据时,它不起作用。
  • 您的示例运行正常,有什么问题?
  • 我不想像示例那样获取数据,而是从本地保存的 json 文件中获取数据。过滤器将在写入数据的表中过滤掉
  • 那么从 json 获取数据有什么大不了的呢?你试过什么?

标签: javascript angular typescript


【解决方案1】:

按照 Richard 所说的那样发布您的代码后,您应该将 Pipe 更改为 countrysearch,如下所示,

  <li *ngFor="let country of Countries | countrysearch : searchText">
        {{countries.Name}}
 </li>

并使用 null 处理顺序和属性过滤修改您的管道 Name 以避免出现以下任何错误,

export class CountrysearchPipe implements PipeTransform {
  transform(Country: any[], searchText: string): any[] {
    if(!Country) return [];
    if(!searchText) return Country;
    if(Country && Country.length > 0){
searchText = searchText.toLowerCase();
return Country.filter( it => {
      return it.Name.toLowerCase().includes(searchText);
    });
   }
  }
}

【讨论】:

  • 嘿,谢谢,现在我收到错误“TypeError:it.toLowerCase 不是函数”
  • 当我在搜索字段中输入所有内容时,都会删除所有内容,但出现 0 个错误
  • 如上所述,通过 stackblitz 重现您的问题
  • “这是一个相当大的项目”我认为这不可能
  • 老兄,实际答案在我这里。
【解决方案2】:

问题是因为你的管道名称是 countrysearch 但在你的 html 文件中你写了 filter: searchText 它应该是 countrysearch: searchText

在您的 pipe.ts 中的其他地方将名称更改为 filter 而不是 countrysearch

【讨论】:

  • 嗨,谢谢你的回复,现在我进入控制台“AppComponent.html:9 ERROR TypeError: it.toLowerCase is not a function”你知道这可能意味着什么吗?跨度>
  • 在你当前拥有it.toLowerCase()的return语句中写成it.toString().toLowerCase()
  • 当我这样做时,它会在控制台中给出 0 个错误。但这会使搜索结果消失,表格继续显示,我输入的速度为 0 个结果
  • 在editor link 解决了您的代码,您只需转到 pipe.filter.ts 代码并添加 return it.Name.toString().toLowerCase().includes(searchText); 代替 return it.toString().toLowerCase().includes(searchText); 它过滤了整个对象,而不仅仅是名称
  • 没关系,我们都在学习中:)您可以标记您认为合适的答案。
猜你喜欢
  • 1970-01-01
  • 2019-07-04
  • 2017-06-09
  • 2017-07-25
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
相关资源
最近更新 更多