【问题标题】:Is there a way to filter material table based on date有没有办法根据日期过滤材料表
【发布时间】:2019-06-10 06:58:17
【问题描述】:

我正在尝试使用 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);
};
}  }

这个函数可以从 datepicker 中选择不工作的日期 -

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);
};

【问题讨论】:

  • 是的,你可以!您能否提供一些示例数据,特别是针对startTime
  • { name: '测试脚本', startTime: '5/1/2019 17:43:09', endTime: '1/5/2019 17:43:19',status:'running '} .. 这是我正在做过滤器的对象
  • 所以你需要为startTime 使用管道,正如你所看到的,它包含时隙也控制台filterValue 变量的值
  • 不能使用角材质内置滤镜吗??
  • 检查发布的答案

标签: angular filter datepicker angular-material


【解决方案1】:

使用M/d/yyyy 格式从 DatePicker 解析日期,如:

this.datepipe.transform(filterValue, 'M/d/yyyy');

根据您的 JSON 数据,它实际上不包含前导零。

Working_Demo

我从日期选择器中选择了1st May 2019,并得到了结果中的第一条记录。

编辑:

你需要注册一次filterPredicate,然后你可以设置DataSourcefilter属性

所以只需在constructorngOnInit() 方法中注册它,例如:

constructor(public datepipe: DatePipe) {
    this.dataSource.filterPredicate = (data, filter: string) => 
        !filter || data.startTime.includes(filter);
}

点击事件:

this.dataSource.filter = filterValue.trim();

【讨论】:

  • 是的,现在它工作了..我不知道因为这个小错误它没有工作..非常感谢!!!
  • 欢迎您!如果有帮助,请随时接受答案!
  • 我第一次注意到一件事,当您进行过滤时,它不只返回开始时间,而是同时返回......为什么会发生这种情况......只需在您的演示中将结束时间更改为与开始时间相同会知道问题的。
  • @Priyanka 是的,刚刚检查了已更新的答案和演示也
  • 是的,它的工作原理.. 所以我只是在 ngOnInit-this.dataSource.filterPredicate = (data, filter: string) => { if(this.type=='start') return data .startTime.includes(过滤器);其他{返回data.endTime.includes(过滤器); }
猜你喜欢
  • 2019-12-27
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 2021-04-06
  • 2012-06-17
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多