10

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?

Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
ill
  • 352
  • 2
  • 4
  • 23

4 Answers4

31

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.

pouya zad
  • 958
  • 1
  • 10
  • 15
  • it does ... =) +1 – ill Mar 19 '18 at 13:17
  • Works for me, thanks! Why does that happens? Shouldn't it work like (change) method? – Kevin Amorim Jun 10 '20 at 16:25
  • 2
    Binding to this in the view causes issues with change detection and prevents any dates in the calendar from being clickable. The filter function should be bound to this ahead of time. See https://github.com/angular/components/issues/21929 – Ruben Aug 08 '22 at 02:18
8

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

Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
mohit uprim
  • 5,226
  • 2
  • 24
  • 28
  • 1
    Hmmmn .. I should have tried this definition of a filter function earlier. My definition of the filter was originally 'dateFilter(d: date) {' In that case the access to 'this.' is not working ... In my presented code it is ... sorry for the inconsistencies – ill Nov 09 '17 at 14:57
  • i prefer this solution instead of .bind(this), as this would not trigger change detection like .bind(this) does every second. thanks. – Krunal Limbad Dec 29 '21 at 07:43
0

Type '(d: Date) => boolean' is not assignable to type 'DateFilterFn<Date | null>'

myFilter = (d: Date ** |null **): boolean => {
   const day = (d || new Date()).getDay();
   // Prevent Saturday and Sunday from being selected.
   return day !== 0 && day !== 6;
};
0

You can

myLegalDate = (d: Date): boolean => {
    //Your code
    //You can see the variable someDateToBlock
    console.log(this.someDateToBlock);
}

myFilter = this.myLegalDate.bind(this);