Angular 9-연장하는 방법 (로케일 인식주의 시작) NativeDateAdapter가 작동합니까?

Dec 02 2020

로케일을 인식하기 위해 (주 시작과 관련하여) Material DatePicker이 확장 기능을 만들었습니다.

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);
  }
}

나는 또한 0 args 생성자로 시도하고 지속적으로 1을 요일로 되 돌렸다. 일부 동료는 {providedIn: 'root'}도움 이 될 수 있다고 말했습니다 .

app.module.ts공급자로 연결했습니다 .

{
  provide: DateAdapter,
  useClass: LocaleDateAdapter
}

내 DatePicker는 다음과 같이 설정됩니다.

<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>

문제는 내 LocaleDateAdapter가 인스턴스화되지 않았고 (중단 점이 적중되지 않음)주의 시작이 변경되지 않고 월요일로 변경되어야한다는 것입니다.

작동시키는 방법?

답변

Mikelgo Dec 02 2020 at 16:47

나는 스택 블리츠를 준비했다 .

나는 당신이했던 것과 거의 똑같습니다. 그러나 가장 큰 차이점은 (문제가 왜 작동하지 않는지) platform.

NativeDateAdapter두 번째 인수로 요구하면 의해 주입 할 수있는 플랫폼 ID @Inject(PLATFORM_ID)확인 올바른 플랫폼 ID가 각도의 DI에 의해 제공되는이 있습니다.

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

의 구현은 getFirstDayOfWeek당신이 한 것처럼 괜찮습니다.

참고 : 내 예에서는 독일의 값 AppModule으로 강제로 사용 LOCALE_ID하므로 de. 예를 들어이를 재정의 할 수도 있습니다 en-US. 또한 주석 처리 registerLocaleData하거나 전체 공급자를 제거 해야합니다 . 그러면 일요일의 첫 번째 요일로 표시됩니다.

생성자가 실행되지 않는 이유는 약간 의심 스럽습니다. 여기 내 추측은 이것이 모듈 구조와 관련이 있다는 것입니다.