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
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.
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();
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With