Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open angular mat-datepicker from typescript

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

like image 271
Helene Avatar asked Jun 01 '18 08:06

Helene


3 Answers

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.

like image 98
Faisal Avatar answered Oct 20 '22 05:10

Faisal


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();
   }
}
like image 42
Anshuman Jaiswal Avatar answered Oct 20 '22 04:10

Anshuman Jaiswal


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();
  }
}
like image 2
HaniBhat Avatar answered Oct 20 '22 05:10

HaniBhat