Angular Material 2 DatePicker with only month and year

Viewed 21523

I was looking for a way to make the angular material datepicker 2 change to only year and month mode but it does not have that option in the documentation

I can set the startView but when month or year is selected, change to Day mode

<md-form-field>
     <input mdInput [mdDatepicker]="picker" placeholder="Choose a date">
     <md-datepicker-toggle mdSuffix [for]="picker"></md-datepicker-toggle>
     <md-datepicker #picker startView="year" [startAt]="startDate"></md-datepicker>
</md-form-field>

I want this: https://plnkr.co/edit/eV2Kmt?p=preview

But that plunker is in angular material 1

Any help? :)

3 Answers

Looks like there's soon gonna be year support soon, once this PR is merged!

(However, it appears that it probably will appear in release 5.1 since it was placed in milestone 5.1)

In HTML

<mat-datepicker #searchDate startView="year" (monthSelected)="monthSelectedHandler($event)"></mat-datepicker>

In your controller

searchDateValue: FormControl;

ngOnInit() {
    this.searchDateValue = new FormControl(this.searchDate);
}

monthSelectedHandler(event) {
    const date = new Date(`${event._i.month + 1}/${event._i.date}/${event._i.year}`);
    this.searchDateValue.setValue(date);
    this.searchDatePicker.close();
}
Related