Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MatDatepickerFilter - Filter function can't access class variable

A MatDatePicker with a filter defined as followed:

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

I would like to access the variable someDateToBlock (or any other) in the filter function. Is there a workaround to make this possbile?

like image 437
ill Avatar asked Nov 09 '17 14:11

ill


2 Answers

I had the same issue, seems like material date picker doesn't have access to "this" of the component for filter function. For me changing:

[matDatepickerFilter]="myFilterFunction" 

to

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

did the trick.

like image 84
pouya zad Avatar answered Nov 10 '22 07:11

pouya zad


This is working, here is plunkr link: 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;
  }
}

I checked with alert(this.someDateToBlock) also

like image 39
mohit uprim Avatar answered Nov 10 '22 07:11

mohit uprim