Material datepicker doesn't set start value when clicking on input field

212 Views Asked by At

I use material date picker with startAt binding to set the default selected value. I have also enabled the user to click on the input field to open the calendar overlay to select the date. I have done this by adding (click), (focus) event binding.

the problem is, when clicking on the input field, it doesn't set the startAt value. however when the calendar toggle icon is clicked, it correctly shows the selected value.

I reproduced this issue in stackblitz here

In the above example, you can check that when clicking on the input field it doesn't set the tomorrow's date, however it sets it correctly when clicking on the toggle button

I am not sure if i am missing some basic config or is this really a bug/limitation. would appreciate any help

tried adding click event and focus event separately and also tried adding both together but still the same issue persists

was able to reproduce the issue using a simple setup in stackblitz

1

There are 1 best solutions below

0
D A On

It doesn't because you will have to set the input value yourself:

<mat-form-field>
  <input
    matInput
    [matDatepicker]="picker"
    (click)="setOnOpen()"
    (focus)="setOnOpen()"
    placeholder="Choose a date"
    [value]="tomorrow"
  />
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker [startAt]="tomorrow"></mat-datepicker>
</mat-form-field>

and:

  import { Component, ViewChild } from "@angular/core";
  import { MatDatepicker } from "@angular/material";

  /** @title Basic datepicker */
  @Component({
    selector: "datepicker-overview-example",
    templateUrl: "datepicker-overview-example.html",
    styleUrls: ["datepicker-overview-example.css"]
  })
  export class DatepickerOverviewExample {

    //tomorrow = new Date(); 
  @ViewChild('picker',{static:true}) picker!: MatDatepicker<Date>;

    tomorrow:Date | undefined = undefined;

    constructor() {
    // this.tomorrow.setDate(this.tomorrow.getDate() + 1);
    }
    setOnOpen()
    {
      this.picker.open();
      if (this.tomorrow === undefined)
          this.tomorrow = new Date(new Date().setDate(new Date().getDate() + 1));        }
  }