Angular 6 material - how to get date and time from

2020-02-29 01:06发布

问题:

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

回答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.

  1. MaterialTimeControl - Material Design with Angular Material, CDK, and Flex Layouts

  2. amazing-time-picker - Not built with Angular Material, but built to be compatible with it

  3. date-time-picker - Not fully Material Design, but built with the CDK



回答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';


回答3:

this is my component.html code

      <mat-form-field>
          <input matInput ngModel name="dateofbirth" [matDatepicker]="dateofbirth" #dateofbirth="ngModel" placeholder="Choose your Birth Date" required dateofbirth>
          <mat-datepicker-toggle matSuffix [for]="dateofbirth"></mat-datepicker-toggle>
          <mat-datepicker  #dateofbirth startView="year" [startAt]="startDate"></mat-datepicker>
        </mat-form-field>

this is my component.ts code

onSignup(form: NgForm)
 {
    if (form.invalid) {
      return;
    }

    this.authService.createUser(
      this.id,
      form.value.dateofbirth);

      console.log(form.value.dateofbirth)
  }

hope it helps for you...as it did for me thank you!!!



标签: angular