Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable specific dates using Angular Material Datepicker?

I would like to disable weekends and specific dates in Angular Material Datepicker component.

How can I do that?

app.component.html:

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

package.json:

"dependencies": {
    "@angular/animations": "^5.1.3",
    "@angular/cdk": "^5.0.3",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/material": "^5.0.3",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"
  },
like image 816
codedamn Avatar asked Jan 09 '18 13:01

codedamn


1 Answers

You need the matDatepickerFilter, use it like so:

 <mat-form-field>
     <input matInput
        [matDatepicker]="picker"
        [matDatepickerFilter]="dateFilter"
        placeholder="Choose a date">
     <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
     <mat-datepicker #picker></mat-datepicker>
 </mat-form-field>

and in your component eg someComponent.ts:

@Component({...})
export class SomeComponent.ts {
...
    dateFilter = (date: Date) => date.getMonth() % 2 == 1 && date.getDate() % 2 == 0;
...
}

... stands for some other stuff, filtering is just an example of filtering odd month, you can use any, general it must be function that returns boolean and accepts date

reference example project

reference docs

like image 122
Dmytro Grynets Avatar answered Oct 21 '22 11:10

Dmytro Grynets