der*_*itz 5 angular-material angular
为了了解语言环境(关于本周开始)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);
}
}
Run Code Online (Sandbox Code Playgroud)
我还尝试使用 0 args 构造函数并不断重新调整 1 作为一周的第一天。一些同事说这{providedIn: 'root'}可能会有所帮助——但没有。
我把它app.module.ts作为提供者连接起来:
{
provide: DateAdapter,
useClass: LocaleDateAdapter
}
Run Code Online (Sandbox Code Playgroud)
我的 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>
Run Code Online (Sandbox Code Playgroud)
问题是我的 LocaleDateAdapter 没有实例化(断点未命中)并且一周的开始没有改变 - 应该改为星期一。
如何使它工作?
我准备了一些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);
}
Run Code Online (Sandbox Code Playgroud)
的实现getFirstDayOfWeek和你一样很好。
注意:在我的示例中,AppModule我强制使用LOCALE_ID德国的值,因此de. 您还可以使用例如覆盖它en-US。您还需要注释掉然后registerLocaleData删除整个提供程序。那么您应该将星期日视为一周的第一天。
为什么你的构造函数没有被执行有点可疑。我的猜测是这与你的模块结构有关。
| 归档时间: |
|
| 查看次数: |
570 次 |
| 最近记录: |