aryan
aryan

Reputation: 115

Angular Material Date picker disable the year selection

I am trying to disable the year selection in angular material date picker.

I've created custom native date adapter to dispaly the date when selected from the date picker. In this case year is disable so user can't able to change the year.

import { NativeDateAdapter } from '@angular/material';

export class AppDateAdapter extends NativeDateAdapter {
  months = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec'
  ];

  format(date: Date, displayFormat: Object): string {
    if (displayFormat === 'input') {
      const day = date.getDate();
      const month = this.months[date.getMonth()]; // date.getMonth() + 1;
      const year = date.getFullYear();
      let days: any;
      if (day <= 9) {
        days = '0' + day;
      } else {
        days = day;
      }
      return `${days}` + '-' + `${month}` + '-' + `${year}`;
    }
    return date.toDateString();
  }
}

Upvotes: 1

Views: 7249

Answers (1)

Seyhmus Gokcen
Seyhmus Gokcen

Reputation: 248

From the angular material docs;

As with any standard <input>, it is possible to disable the datepicker input by adding the disabled property. By default, the <mat-datepicker> and <mat-datepicker-toggle> will inherit their disabled state from the <input>, but this can be overridden by setting the disabled property on the datepicker or toggle elements. This can be useful if you want to disable text input but allow selection via the calendar or vice-versa.

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp1" placeholder="Completely disabled" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp1"></mat-datepicker-toggle>
    <mat-datepicker #dp1></mat-datepicker>
  </mat-form-field>
</p>

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp2" placeholder="Popup disabled">
    <mat-datepicker-toggle matSuffix [for]="dp2" disabled></mat-datepicker-toggle>
    <mat-datepicker #dp2></mat-datepicker>
  </mat-form-field>
</p>

<p>
  <mat-form-field>
    <input matInput [matDatepicker]="dp3" placeholder="Input disabled" disabled>
    <mat-datepicker-toggle matSuffix [for]="dp3"></mat-datepicker-toggle>
    <mat-datepicker #dp3 disabled="false"></mat-datepicker>
  </mat-form-field>
</p>

for further information please see:

https://material.angular.io/components/datepicker/overview

Upvotes: 0

Related Questions