Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material 2 DatePicker, change display format dynamically

I'm using Angular 2 Material's DatePicker component here, and I want to be able to dynamically set the display format of (i.e. YYYY-MM-DD or DD-MM-YYYY, etc.)

There seems to be a way to extend this globally by overriding the used "Date Adapter", but that doesn't work for me because I potentially need different date time pickers to have different formats. I can't set it globally. Is there any known workaround for this?

like image 905
Carlos Rodriguez Avatar asked Aug 01 '17 20:08

Carlos Rodriguez


1 Answers

You can create another input which will display formated date value. In your html create one input for ngModel and matDatepicker, and another one to display formatted date value.

<div style="position: relative">
  <!-- display formatted value -->
  <mat-form-field>
    <input
      matInput
      [value]="currentDate | dateFilter: dateFormat"
      [placeholder]="label"
      autocomplete="off"
    />

    <!--shadow input keep ngModel value-->
    <input
      [matDatepicker]="picker"
      [(ngModel)]="value"
      class="shadow-dateInput"
    />
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
  </mat-form-field>
</div>

Here is a working example on Stackblitz

like image 86
Armen Stepanyan Avatar answered Nov 14 '22 02:11

Armen Stepanyan