Angular 4 - 在按钮单击时应用过滤器

标签 angular observable

我在按钮点击事件的垫表上应用过滤器时遇到问题。

component.html 中的按钮:

<button #button mat-raised-button color="primary" (click)="applyFilter();" value="2017-01">January</button>

component.ts applyFilter方法调用:

 @ViewChild('button') button: ElementRef;

applyFilter(){
Observable.fromEvent(this.button.nativeElement, 'click')
  .distinctUntilChanged()
  .subscribe(() => {
    if (!this.dataSource) { return; }
    this.dataSource.filter = this.button.nativeElement.value;
  })};

输入字段上的过滤器效果很好,但是当我尝试在按钮上添加 @ViewChild 时,我在控制台输出中收到错误,例如:

ERROR TypeError: Invalid event target

我找不到任何有关 .fromEvent rxjs 的文档,因此任何帮助都会很棒。谢谢

编辑:

这部分代码工作正常:

    <mat-form-field floatPlaceholder="never">
  <input matInput #filter placeholder="Search">
</mat-form-field>

      Observable.fromEvent(this.filter.nativeElement, 'keyup')
    .distinctUntilChanged()
    .subscribe(() => {
      if (!this.dataSource) { return; }
      this.dataSource.filter = this.filter.nativeElement.value;
    });

我想用 12 个按钮(几个月)隐藏/替换输入字段,每个按钮都会在 mat-table 上应用特定的过滤器

最佳答案

你可以尝试这样的事情: HTML:

<button #button mat-raised-button color="primary" (click)="this.customFilter = getMonth('01'); changeFilter($event)">January</button>

<input [(ngModel)]="this.customFilter"  #filter matInput placeholder="Search">

组件.ts:

changeFilter(event){
  this.dataSource.filter = this.customFilter;
};
getMonth(val){
  let date: any = new Date();
  let yyyy = date.getUTCFullYear();
  return yyyy+'-'+val;
}
Observable.fromEvent(this.filter.nativeElement, 'keyup')
  .distinctUntilChanged()
  .subscribe(() => {
    if (!this.dataSource) { return; }
    this.dataSource.filter = this.filter.nativeElement.value;
  });

关于Angular 4 - 在按钮单击时应用过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47012225/

相关文章:

php - 如何将 PHP 作为后端、MySQL 作为数据库的 Angular 5 应用程序部署到 AWS

android - 在 NativeScript Angular 中,为什么这些图标不居中显示?

javascript - Firestore 可观察或 promise

arrays - Angular 6 - 从可观察的数据中获取数据我做错了什么?

angular - 如何从项目中保存 id 以在下一页上显示特定数据( Angular 4)

Angular react 形式

javascript - Regex - 带有 .和 ,

javascript - 重新分配 Observable Array 时订阅者未更新,但在将对象推送到数组时收到通知

android - 了解 RxJava 基础知识

javascript - 如何组合 2 个或多个 observables 以便您知道哪个发出了?