I'm working on an angular project and I was looking for a way to make the angular material datepicker change to select month first and then the year second (no needs day).
This is my current code:
example.component.ts
import { of } from 'rxjs';
public isMonthOpened = true;
public chosenMonthHandler(normalizedMonth: moment.Moment, datepicker: MatDatepicker<moment.Moment>, dateFormControl: FormControl, date: Date): void {
normalizedMonth = moment(normalizedMonth);
const ctrlValue = dateFormControl.value;
ctrlValue.month(normalizedMonth.month());
dateFormControl.setValue(moment(ctrlValue));
this.isMonthOpened = false;
date.setMonth(ctrlValue.toDate().getMonth());
// the datepicker does not re-open after closing if I do not set a delay
of(datepicker.close()).subscribe(() => {
setTimeout(() => {
datepicker.open();
}, 250);
});
}
public chosenYearHandler(normalizedYear: moment.Moment, datepicker: MatDatepicker<moment.Moment>, dateFormControl: FormControl, date: Date): void {
normalizedYear = moment(normalizedYear);
const ctrlValue = moment(dateFormControl.value);
ctrlValue.year(normalizedYear.year());
dateFormControl.setValue(ctrlValue);
datepicker.close();
date.setFullYear(ctrlValue.toDate().getFullYear());
this.isMonthOpened = true;
}
example.component.html
<mat-form-field appearance="outline" class="custom-form-field" (click)="startDP.open()">
<mat-label>Start</mat-label>
<input matInput [matDatepicker]="startDP" #startDPInput [formControl]="startDateFormControl" />
<mat-datepicker-toggle matSuffix [for]="startDP"></mat-datepicker-toggle>
<mat-datepicker
#startDP
[startView]="isMonthOpened ? 'year' : 'multi-year'"
(yearSelected)="chosenYearHandler($event, startDP, startDateFormControl, _startDate)"
(monthSelected)="chosenMonthHandler($event, startDP, startDateFormControl, _startDate)"
>
</mat-datepicker>
</mat-form-field>
Is there a better way to do that?