为了获得一个地区感知(关于本周开始)的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没有实例化(断点没有命中),一周的开始也没有改变--应该改到星期一。
如何让它工作?
发布于 2020-12-02 17:47:55
我准备了一些stackblitz。
我做的和你做的差不多。然而,主要的区别(我猜这就是问题所在,为什么它对你不起作用)是,你如何提供platform。
NativeDateAdapter需要平台id作为第二个参数,您可以通过@Inject(PLATFORM_ID)注入它,这可以确保Angular的DI提供正确的平台id。
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,或者只是删除整个提供程序。那么你应该看到一周的第一天是星期天。
为什么你的构造函数没有被执行就有点可疑了。我的猜测是,这与您的模块结构有关。
https://stackoverflow.com/questions/65104948
复制相似问题