【问题标题】:fire angular pipe event when button is clicked单击按钮时触发角管道事件
【发布时间】:2019-08-08 23:15:32
【问题描述】:

我想在单击按钮时实现 angular 5 搜索管道。

我有一个输入框,它将接收自定义搜索值,并从对象数组中过滤不同的键值。我在输入输入文本时实现了角管道,它会搜索,但我想在仅单击用户输入和搜索按钮时触发此操作。无论如何我们可以做到这一点。我被困在实现点击事件

itemsearch.pipe.ts

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

@Pipe({
name: 'itemsearch'
})
export class ItemsearchPipe implements PipeTransform {

  public transform(value, keys: string, term: string) {

if (!term) {
  return value;
}
return (value || []).filter(item => keys.split(',').some(key => 
 item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));

} }

 itemcomponent.ts


<div *ngFor="let item of items | itemsearch:'name, age':query"> 
{{item.name}}
         {{item.age}} </div>
</div>

【问题讨论】:

标签: angular filter onclick pipe


【解决方案1】:

您可以做的是从*ngFor 中删除管道运算符并将逻辑移动到您的组件中

组件.ts

import { ItemsearchPipe } from ...

search() {
   // you can do whatever you want here, return the value or store it in a variable
   this.items = this.ItemsearchPipe.transform(value, keys, term); 
}

然后在你的html中

<div *ngFor="let item of items">
  <!-- ... -->
</div>
<button (click)="search()"></button>

当使用管道运算符时,它基本上会在每次值更改时调用管道函数,当您将逻辑移动到组件中时,您可以控制何时调用管道函数

【讨论】:

    【解决方案2】:

    我制作示例来实现您的想法。

    https://stackblitz.com/edit/angular-8ewarg

    提示:输入的 var 查询不应与绑定到搜索文本框的对象相同。我们应该有另一个用于文本框映射的对象。单击搜索后,将搜索文本框中的新值绑定到“查询”对象。

    魔法!!!

    快乐编码:D

    【讨论】:

    • @ Duy Doan 我想在 UI 上呈现之前访问过滤/管道项目数组。我试图通过 ItemsearchPipe 的实例进行访问,但我得到的只是对象而不是值
    猜你喜欢
    • 2012-03-14
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 2015-10-18
    • 2020-02-20
    • 2017-10-14
    • 2019-07-05
    相关资源
    最近更新 更多