我在按钮点击事件的垫表上应用过滤器时遇到问题。
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/