0

I'm trying to implement Month and Year only in Angular Material Datepicker (based in their docs). I noticed that by default, it's getting the current day. For example the date today is June 13, 2019 and I selected May(month) 2019(year) and it returns May 13, 2019.

What I am thinking now is to make the day default as 1 so it would result into May 1, 2019 or Feb 1 or Mar 1 etc. How would I do that?

UPDATE: I already solved this part by setting the value like this in component file

this.form = new FormGroup({
   date: new FormControl(moment().startOf('month'), validators: [Validators.required]
});

If in case I selected May 31st and assuming the current month is June and have no 31st, I'm expecting to have it returned as June 30 but what happens is it became June 1. Is this a bug?

RJB
  • 95
  • 3
  • 15
  • Oh, I just realised I have posted an answer without reading the edit.. I guess you only require help in setting it to the first date of the month? – wentjun Jun 13 '19 at 03:23

1 Answers1

1

You can make use make use of the monthSelected event binding such that a method will be triggered whenever you have selected a month.

First, we bind the monthSelected event to the onMonthSelect() method.

<mat-form-field>
  <input matInput [(ngModel)]="selectedDate" (ngModelChange)="onDateSelect($event)" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker (monthSelected)="onMonthSelect($event)"  #picker></mat-datepicker>
</mat-form-field>

And on your component.ts, we we bind selectedDate such that the first day of the month will be selected.

onMonthSelect(event) {
  this.selectedDate = new Date(event.getFullYear(), event.getMonth(), 1);
}

Here's a demo.

wentjun
  • 40,384
  • 10
  • 95
  • 107