Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 9 - how to get extended (Locale aware start of week) NativeDateAdapter working?

To get a Locale aware (in regards of start of the week) Material DatePicker i created this extension:

import { Injectable } from "@angular/core";
import { LOCALE_ID, Inject } from "@angular/core";
import { Platform } from "@angular/cdk/platform";
import { getLocaleFirstDayOfWeek } from "@angular/common";
import { NativeDateAdapter } from '@angular/material/core';

@Injectable({providedIn: 'root'})
export class LocaleDateAdapter extends NativeDateAdapter {
  constructor(@Inject(LOCALE_ID) public locale: string) {
    super(locale, new Platform());
  }

  getFirstDayOfWeek() {
    return getLocaleFirstDayOfWeek(this.locale);
  }
}

I also tried with 0 args constructor and constantly retuning 1 as first day of week. Some colleague told that {providedIn: 'root'} might help - it did not.

I hooked it in app.module.ts as provider:

{
  provide: DateAdapter,
  useClass: LocaleDateAdapter
}

my DatePicker is set up like this:

<mat-form-field appearance="fill">
  <mat-label>set date</mat-label>
  <input matInput [matDatepicker]="picker1" (dateChange)="onDateChange($event)" [formControl]=formDate>
  <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
  <mat-datepicker [startAt]="filter.date"  #picker1></mat-datepicker>
</mat-form-field>

The problem is that my LocaleDateAdapter is not instantiated (Breakpoint not hit) and the start of the week isn't changing - should change to Monday.

How to make it work?

like image 339
dermoritz Avatar asked Nov 06 '22 03:11

dermoritz


1 Answers

I prepared some stackblitz.

I did more or less the same what you did. However the main difference (and I guess thats the problem, why it is not working for you) is, how you provide the platform.

The NativeDateAdapter needs as second argument the platform id which you can inject by @Inject(PLATFORM_ID) This makes sure that the correct platform id is provided by Angular's DI.

export class CustomDateAdapter extends NativeDateAdapter {
  constructor(
    @Inject(LOCALE_ID) public locale,
    @Inject(PLATFORM_ID) platformId
  ) {
    super(locale, platformId);
  }

The implementation of getFirstDayOfWeek is fine as you did.

Note: in my example in AppModule I'm forcing to use as LOCALE_ID the value for Germany, so de. You can also override it with e.g. en-US. You also need to comment out then registerLocaleData or just remove the whole provider. then you should see as first day of the week Sunday.

Why your constructor is not executed is a bit suspicious. My guess here would be that this has something to do with your module structure.

like image 189
Mikelgo Avatar answered Nov 11 '22 11:11

Mikelgo