MatDatepickerFilter - 过滤函数无法访问类变量

时间:2017-11-09 14:26:43

标签: angular-material2 datefilter

MatdatePicker,其过滤器定义如下:

<mat-form-field class="example-full-width">
  <input matInput [matDatepickerFilter]="myFilter" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
export class DatepickerFilterExample {
  someDateToBlock: number = 3;
  myFilter = (d: Date): boolean => {
    const day = d.getDay();
    // THIS FUNCTION CANNOT ACCESS THE VARIABLE 'someDateToBlock'
    return day !== 0 && day !== 6;
  }
}

我想在filter函数中访问变量some​​DateToBlock(或任何其他)。是否有解决方法使这个可能吗?

2 个答案:

答案 0 :(得分:9)

我遇到了同样的问题,似乎物料日期选择器无法访问过滤功能组件的“this”。对我而言:

[matDatepickerFilter]="myFilterFunction" 

[matDatepickerFilter]="myFilterFunction.bind(this)"

做了这个伎俩。

答案 1 :(得分:1)

这是有效的,这里是plunkr链接:https://plnkr.co/edit/oRGfxLSrn6GdfRhYO1rr?p=preview

export class DatepickerOverviewExample {
  someDateToBlock: number = 3;
  myFilter = (d: Date): boolean => {
    const day = d.getDay();
    // THIS FUNCTION CANNOT ACCESS THE VARIABLE 'someDateToBlock'
    return this.someDateToBlock;
  }
}

我用alert(this.someDateToBlock)检查了