【问题标题】:How can I make a filter for based text input value with indexof() in angular如何使用角度的 indexof() 为基于文本输入值的过滤器
【发布时间】:2022-08-23 22:04:01
【问题描述】:

我已经用下面的 sn-p 实现了一个角度过滤功能,它工作正常:

 export class FilterPipe implements PipeTransform {
    transform(prsnl: prsnlFrontStateInterface[], filterText: string) {
        if(prsnl.length === 0 || filterText === \'\'){
          return prsnl;
        }else{
          return prsnl.filter((prsnl) => 
          { return prsnl.firstname.toLowerCase() === filterText.toLowerCase()
          })
        }
        
      }
    
    }

但问题是它只有在输入过程完成并且输入的单词与api值匹配时才会显示过滤结果,因为我使用了“===”运算符来制作过滤器。现在我希望它即使在输入过程中也开始过滤,即输入未完成并且输入的单词是数据或现有数据的一部分,类似于 SQL 或 JAVA 中的 LIKE 运算符。因为 LIKE 不是 typescript 执行此操作的运算符,所以我宁愿使用 javascript 的 indexof() 方法来执行此操作:

export class FilterPipe implements PipeTransform {

  transform(prsnl: prsnlFrontStateInterface[], filterText: string) {
    if(prsnl.length === 0 || filterText === \'\'){
      return prsnl;
    }else{
         return prsnl.filter((prsnl) => 
           prsnl.firstname.indexOf(filterText) > -1);
    }
    
  }

}

编辑:添加 Html 部分

补偿

<div class=\"main\">
          <div class=\"input-group\">
            <input type=\"text\" class=\"form-control\" placeholder=\"Seach by name\" [(ngModel)]=\"filterText\">
            <div class=\"input-group-append\">
              <button class=\"btn btn-secondary\" type=\"button\">
                <i class=\"fa fa-search\"></i>
              </button>
            </div>
          </div>  
        </div>

但它不起作用,我想知道为什么,因为 \"filterText\" 是提供的输入文本值。有人可以指导我使用 indexOf() 有什么问题吗?或者还有其他我看不到的错误吗?我非常感谢任何帮助找出问题所在。

  • 我可以看到您的“过滤器”功能没有任何问题。您能否提供一个最小的可重现示例? Playground example
  • @迈克。谢谢看槽。我不熟悉制作可复制的示例(我会这样做)所以我更新了问题以包括 Html 部分。基本上我用命令行创建了 filterPipe 并将其导入到 appModule 中。第一个过滤类工作正常,但使用 indexOf() 方法的第二个是失败的,当我从输入字段搜索时,即使使用现有名称,它也不会呈现任何内容,所以我猜这是我的代码的问题第二个实现。

标签: angular typescript filter indexof


【解决方案1】:

我认为您的代码中没有任何问题,您可以尝试包含它与'LIKE' 的工作方式相同。

export class FilterPipe implements PipeTransform {

  transform(prsnl: prsnlFrontStateInterface[], filterText: string) {
    if(prsnl.length === 0 || filterText === ''){
      return prsnl;
    }else{
         return prsnl.filter((prsnl) => 
           prsnl.firstname.includes(filterText));
    }
    
  }

}

用例https://stackblitz.com/edit/typescript-r54kko?file=index.ts

编辑:请告诉您如何使用FilterPipe

【讨论】:

    猜你喜欢
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多