Angular matDatepicker disable date casting

Issue

I want create a simpleDateFormatterDirective to MatDatepicker, for etc:
When i wrote simple 4 or 6 numbers to calendar, the directive replace it to a real date

0123 -> 2021-01-23
200415 -> 2020-04-15

But when i try catch it with blur, matDatePicker try to cast it new Date(inputvalue)
So i catch 0123 – (123-01-01) So can i disable this feature of datepicker or have any other idea to implement this feature?

<mat-form-field appearance="fill" class="example-form-field">
  <mat-label>Choose a date</mat-label>
  <input simpleDateFormatterDirective matInput [matDatepicker]="datepicker">
  <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
  <mat-datepicker #datepicker>
    <mat-datepicker-actions>
      <button mat-button matDatepickerCancel>Cancel</button>
      <button mat-raised-button color="primary" matDatepickerApply>Apply</button>
    </mat-datepicker-actions>
  </mat-datepicker>
</mat-form-field>

Solution

You’ll probably need to create a custom DateAdapter, which is responsible for parsing and formatting dates in material components.

Then you need to provide that adapter at some level of your application – be it root or inside your component.

You can extend a standard NatvieDateAdapter and overwrite methods you require with your custom logic.

You will probably have to also provide MAT_DATE_FORMATS for your usecase – unless you hardcode them in your adapter.

Answered By – TotallyNewb

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.