'Angular 6 material - how to get date and time from matDatepicker?
I have this piece of code in my html:
<mat-form-field>
<input matInput [matDatepicker]="myDatepicker" placeholder="Choose a date" [(ngModel)]="model.value" name="value">
<mat-datepicker-toggle matSuffix [for]="myDatepicker"></mat-datepicker-toggle>
<mat-datepicker #myDatepicker></mat-datepicker>
</mat-form-field>
With this i'm able to get date with this format: YYY-MM-DDThh:mm:ss:millisZ.
Using matDatepicker i'm able to select the date but i need after the date selection to select the time too.
Is possible to achieve this result using matDatepicker ONLY?
Thanks
Solution 1:[1]
No, as of now, it is not possible to choose time from matDatePicker. There is still an open issue on github regarding this feature.
Summary of the issue thread :
Alternatively you can use one of the following to have dateTimePicker for your project.
MaterialTimeControl - Material Design with Angular Material, CDK, and Flex Layouts
amazing-time-picker - Not built with Angular Material, but built to be compatible with it
date-time-picker - Not fully Material Design, but built with the CDK
Solution 2:[2]
If you want a simple solution, then type="time" works. polyfill required for Safari and IE,
Example:
<mat-form-field>
<input matInput type="time" class="bg-none" formControlName="_time" placeholder="Time">
</mat-form-field>
You will have to do the following to polyfill an Angular app
npm i time-input-polyfill
add the following line to polyfill.ts under APPLICATION IMPORTS
import 'time-input-polyfill';
Solution 3:[3]
Even though it's not perfect, nevertheless the mat date picker lets you select date AND time after that, no need for extra libraries, if you accept some compromise.
Here it is.
<mat-form-field>
<input matInput
required
formControlName = "h_Ini"
type="datetime-local"
placeholder="Data Lezione"
>
<mat-datepicker></mat-datepicker>
</mat-form-field>
When you include type="datetime-local" this makes it for dates AND times. The little problem I haven't solved yet is that since this comes with an in-built toggle (that's why there is not additional toggle specified) you can't include for the picker a values-filter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amit Chigadani |
| Solution 2 | |
| Solution 3 | Nicola |
