我正在尝试使用 mat datepicker 根据开始时间和结束时间过滤表。但它不工作。 这是我的 html 代码-
<mat-form-field><input matInput [matDatepicker]="dp1" (keyup)="dateFilter($event.target.value,'start')" (dateInput)="addEvent($event.target.value, $event)" placeholder="Choose a date"><mat-datepicker-toggle matSuffix [for]="dp1" ></mat-datepicker-toggle<mat-datepicker #dp1 ></mat-datepicker>
这是我用于手动输入日期的 ts 文件代码,它可以正常工作-
dateFilter(filterValue : String,input) {
debugger;
this.dataSource.filter = filterValue.trim().toLowerCase();
if(input=='start'){
this.dataSource.filterPredicate = function(data, filter: string): boolean {
return data.startTime.toLowerCase().includes(filter); };} else{ this.dataSource.filterPredicate = function(data, filter: string): boolean {
return data.endTime.toLowerCase().includes(filter);
};
} }
此函数用于从无效的日期选择器中选择日期 -
addEvent(filterValue: string, event: MatDatepickerInputEvent<Date>) {
debugger;
console.log(event.value);
if(event.value!=undefined){
filterValue =this.datepipe.transform(filterValue, 'MM/dd/yyyy');
}
this.dataSource.filter = filterValue.trim();
this.dataSource.filterPredicate = function(data, filter: string): boolean {
return data.startTime.includes(filter);
};
最佳答案
使用 M/d/yyyy
格式解析 DatePicker 中的日期,例如:
this.datepipe.transform(filterValue, 'M/d/yyyy');
根据您的 JSON 数据,它实际上不包含前导零。
我从日期选择器中选择了 2019 年 5 月 1 日
,并得到了结果中的第一条记录。
EDIT:
你需要注册一个filterPredicate
,然后你可以设置DataSource
的filter
属性
所以只需在 constructor
或 ngOnInit()
方法中注册它,例如:
constructor(public datepipe: DatePipe) {
this.dataSource.filterPredicate = (data, filter: string) =>
!filter || data.startTime.includes(filter);
}
点击事件只是:
this.dataSource.filter = filterValue.trim();
关于angular - 有没有办法根据日期过滤 Material 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56521843/