6

I have a select like this :

 <mat-select placeholder="..." (change)="onChange($event.value)">
     <mat-option *ngFor="let option of options" [value]="option.value">
        {{ option }}
     </mat-option>
 </mat-select>
 <div class="disable">
    <mat-form-field>
       <input matInput [matDatepicker]="picker" placeholder="Choose a date">
       <mat-datepicker #picker ></mat-datepicker>
    </mat-form-field>
 </div>

disable class just hide the contain of the div.

In my onChange($event) :

onChange(value) {
   if(value === 'someValue'){
       openDatePicker() //How to do this ??
   }
}

If a specific value is selected i'd like to open the date picker. Is that possible to do this from typescript ?

Thanks for your response

Helene
  • 421
  • 3
  • 9
  • 18
  • see https://stackoverflow.com/questions/45874705/angular-material-2-date-picker-auto-open-on-focus/45874934#45874934 and https://material.angular.io/components/datepicker/api#MatDatepicker – Pengyy Jun 01 '18 at 08:07

3 Answers3

13

You will need to get the datepicker in your code using ViewChild like this:

@ViewChild('picker') datePicker: MatDatepicker<Date>;

Then in your function, you can call the open() method of the datepicker:

onChange(value) {
   if(value === 'someValue'){
       this.datePicker.open();
   }
}

Link to StackBlitz demo.

FAISAL
  • 33,618
  • 10
  • 97
  • 105
4

create object of date picker using ViewChild in TS as:

@ViewChild('picker') datePicker: MatDatepicker;

Use predefined method open of MatDatepicker as:

onChange(value) {
   if(value === 'someValue'){
       this.datePicker.open();
   }
}
Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46
2

To those trying to get this to work on the latest version of Angular, you need to add a second argument to @ViewChild:

  @ViewChild('picker', {read: undefined, static: false}) datePicker: MatDatepicker<Date>;

And reference that object regularly in your function:

onChange(value) {
  if(value === 'someValue'){
    this.datePicker.open();
  }
}
HaniBhat
  • 353
  • 1
  • 9