codedamn
codedamn

Reputation: 861

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"
  },

Upvotes: 14

Views: 16159

Answers (1)

Dmytro Grynets
Dmytro Grynets

Reputation: 953

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

Upvotes: 17

Related Questions