我在按钮点击事件上在mat-table上应用过滤器时遇到问题。
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
时,我在控制台输出中遇到错误,如:
错误类型错误:无效的事件目标
我找不到任何关于.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上应用特定的过滤器
答案 0 :(得分:2)
您可以尝试这样的事情: 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">
Component.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;
});
答案 1 :(得分:0)
如果您的按钮“2017-01”有静态值,那么您可以尝试:
applyFilter(){
if (!this.dataSource) { return; }
this.dataSource.filter = "2017-01";
}
或者按钮值可以更改,请尝试:
<button #button mat-raised-button color="primary" #mybutton (click)="applyFilter(mybutton.value);" value="2017-01">January</button>
applyFilter(value:any){
if (!this.dataSource) { return; }
this.dataSource.filter = value:any;
}