【问题标题】:searchbox in angular 2 doesn't return the whole object角度 2 中的搜索框不返回整个对象
【发布时间】:2021-06-24 05:54:56
【问题描述】:

我对 Angular2 和 4 很陌生。 我有一个类型类 (Item) 的项目列表。 项目字段是名称、价格和描述。 我想在用户输入项目名称时创建一个搜索框,它会显示正确的项目对象。

我遵循了这个例子:http://www.angulartutorial.net/2017/03/simple-search-using-pipe-in-angular-2.html 但它没有用,我认为是因为如果在字符串而不是 item 类型的对象之间进行搜索。

【问题讨论】:

  • 你能发布你的代码吗?

标签: html angular search-box


【解决方案1】:

如果你使用了教程中的代码,你只需要像这样在你的 Angular2 Pipe 中更新 transform 方法的返回语句:

return value.filter(function (el: any) {
                return el.name.toLowerCase().indexOf(input) > -1;
            })

PS:我添加了 el.name 但您可以搜索描述或任何您喜欢的内容。

【讨论】:

    【解决方案2】:

    创建一个自定义管道并将搜索参数传递给该管道,如下例所示

    <li *ngFor="let n of list | FilterPipe: queryString : searchableList ">
          {{n.name}} ({{n.age}})
    </li>
    
     this.searchableList = ['name','age']  
    

    还有你的自定义管道

    @Pipe({
        name: 'FilterPipe',
    })
    export class FilterPipe implements PipeTransform {
        transform(value: any, input: string,searchableList : any) {
            if (input) {
                input = input.toLowerCase();
                return value.filter(function (el: any) {
                    var isTrue = false;
                    for(var k in searchableList ){
                      if(el[searchableList[k]].toLowerCase().indexOf(input) > -1){
                        isTrue = true;
                      }
                      if(isTrue){
                        return el
                      }
                    }
                    
                })
            }
            return value;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 2014-11-29
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多