javascript - 使用 Material Angular 10 的格式更改 Datepicker 的语言
问题描述
我的应用程序中确实有多语言支持,并且希望实现角度材料日期选择器的翻译。我使用了材料中的 dateAdapter 类并设置了值,但是在这样做的同时,我的显示格式正在发生变化。
有人遇到过同样的问题吗?
export const MY_FORMATS = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'ddd, MMM. D YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
@Component({
selector: 'test',
templateUrl: './test.html',
styleUrls: ['./test.scss'],
providers: [{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }],
})
ngOnInit(): void {
//on language change
//change language
this.dateAdapter.setLocale('fr');
}
解决方案
对于多语言支持,我建议您使用MomentDateAdapter。这是 Angular 文档中关于多语言支持和 NativeDateAdapter(默认的)的注释:
MatNativeDateModule 基于 JavaScript 的本机 Date 对象中可用的功能。因此,它不适用于许多语言环境。本机 Date 对象的最大缺点之一是无法设置解析格式。我们强烈建议使用 MomentDateAdapter 或自定义 DateAdapter 与您选择的格式化/解析库一起使用。
唯一的对应物是,通过使用MomentDateAdapter
你现在将拥有moment
一个依赖项......但没什么大不了的,你可能已经在使用它了。
这是一些示例代码(取自 Angular 文档):
import {Component} from '@angular/core';
import {
MAT_MOMENT_DATE_FORMATS,
MomentDateAdapter,
MAT_MOMENT_DATE_ADAPTER_OPTIONS,
} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
/** @title Datepicker with different locale */
@Component({
selector: 'test',
templateUrl: 'test.html',
styleUrls: ['test.css'],
providers: [
// The locale would typically be provided on the root module of your application. We do it at
// the component level here, due to limitations of our example generation script.
{provide: MAT_DATE_LOCALE, useValue: 'fr'},
// `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
// `MatMomentDateModule` in your applications root module. We provide it at the component level
// here, due to limitations of our example generation script.
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
],
})
export class DatepickerLocaleExample {
constructor(private _adapter: DateAdapter<any>) {}
// Change adapter language to japanese
japanese() {
this._adapter.setLocale('ja-JP');
}
}
推荐阅读
- model-view-controller - 如何为 TYPO3 扩展模块设置 newRecordStoragePid?
- postgresql - 日期字段默认为空的数据返回“01-01-1970”
- c# - 更改现有 Azure Key Vault 的访问策略
- php - 默认 XML 和 PHP 文件名
- ios - 如何在 AR Kit 中将 UIImage 添加到场景中
- r - Base R 中的旋转箭头
- javascript - 分派动作后不显示道具
- android - 所有 Http 请求的时间间隔(使用改造和 Rx Java 2)
- python - 在 Python 3.6 中计算多边形和 shapefile 之间的重叠
- ios - UITableViewCell 委托不起作用