6

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?

5
  • What decides which one to use between YYYY-MM-DD and DD-MM-YYYY? Commented Aug 1, 2017 at 21:21
  • Without getting too much into it, I'm getting a bunch of objects back from the server. Each object has a Date and a DateFormat. I want to bind them to their own DatePicker, each displayed in the format associated with it. Commented Aug 1, 2017 at 21:22
  • Honestly, I'd have expected there to have been a simple "dateFormat" input variable on the DatePicker component (that maybe used moment.js behind the scenes) to handle this. I was really surprised to find that that doesn't exist. Commented Aug 1, 2017 at 21:30
  • github.com/angular/material2/issues/5041 github.com/angular/material2/issues/5898 Commented Aug 1, 2017 at 21:40
  • These issues are related, but they don't address the main problem I'm asking about Commented Aug 1, 2017 at 21:56

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.