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

筅森魡賤 提交于 2020-12-08 07:12:35

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/65104948/angular-9-how-to-get-extended-locale-aware-start-of-week-nativedateadapter-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!