angular - Transloco 语言环境。如何添加自定义日期过滤器?
问题描述
我正在尝试将transloco locale默认提供的日期过滤器扩展为其他一些满足我们客户要求的过滤器。但是,文档没有提供关于此的示例或很好的解释。你们中有人设法将自定义过滤器添加到 transloco 语言环境库吗?
我发现东西的唯一地方就是这里,并没有多大帮助。它没有说我应该在哪里调用这些转换器类: https ://ngneat.github.io/transloco/docs/plugins/locale/
我很感激你的时间,伙计们。任何帮助都将受到欢迎。
解决方案
尽管通过使用角管本身,终于得到了一些工作。我不知道其他人是否会觉得这很有用,但这是我的两分钱:
背景:最初的想法是能够创建自定义日期管道,以便我们可以提供特定格式。经过调查,我发现没有一个 transloco locale 服务足以实现我的目标。尽管它们允许您指定日期格式,但您必须坚持使用它们提供的大量选项。(见 LOCALE_DATE_FORMATS 对象) 原意:
import {TranslocoLocaleService} from "@ngneat/transloco-locale";
@Pipe({name: "culturePipe"})
export class CustomDatePipe implements PipeTransform {
public LOCALE_DATE_FORMATS: any = {
"fullDate" : {dateStyle: "medium", timeStyle: "medium"},
"full": {dateStyle: "full", timeStyle: "full"}
};
constructor(private _localeService: TranslocoLocaleService) {
this.locale = _localeService.getLocale();
}
public transform(value: any, format?: string, timezone?: string, locale?: string): string | null {
if (value) {
return this._localeService.localizeDate(value, this.locale, this.LOCALE_DATE_FORMATS[format]);
}
return null;
}
解决方案:我创建了一个自定义日期管道,如下所示:
import {Pipe, PipeTransform} from "@angular/core";
import {TranslocoLocaleService} from "@ngneat/transloco-locale";
import {DatePipe} from "@angular/common";
import {TranslocoService} from "@ngneat/transloco";
import {CultureService} from "@/services/shared-candidates/culture.service";
@Pipe({name: "cultureDatePipe"})
export class CultureDatePipe implements PipeTransform {
private LOCALE_DATE_FORMATS_ES_ES: any = {
....
"longDate": "d 'de' MMMM 'de' y",
...
};
private LOCALE_DATE_FORMATS_EN_US: any = {
...
"longDate": "MMMM d, y",
...
};
private readonly localeDatesFormats: any;
private datePipe: DatePipe;
constructor(private _localeService: TranslocoLocaleService,
private _translationService: TranslocoService) {
let locale = this._localeService.getLocale();
switch (locale) {
case CultureService.SPANISH_LOCALE:
this.localeDatesFormats = this.LOCALE_DATE_FORMATS_ES_ES;
break;
default:
this.localeDatesFormats = this.LOCALE_DATE_FORMATS_EN_US;
}
this.datePipe = new DatePipe(locale);
}
public transform(value: any, format?: string, timezone?: string, locale?: string): string | null {
if (value) {
return this.datePipe.transform(value, this.localeDatesFormats[format], undefined, this._translationService.getActiveLang());
}
}
}
用法:
以编程方式
constructor(...
private _dateTransform: CultureDatePipe) {
}
...
let date = this._dateTransform.transform(dueDateISO, "longDate");
...
排队
<div class="date-line">{{params.date | culturePipe : "longDate" }}</div>
推荐阅读
- actions-on-google - 如何让 Google Assistant 中的电话号码可点击?
- python - 如何使用 Python 重新组合列表中的“子列表”?
- django - 如何将用户上传的 html 文件呈现为页面?姜戈
- docker - 通过 ngrok 暴露后端 docker 容器
- python - 重新读取excel而不格式化日期
- python - 合并同一数组中的值(Python)?
- laravel - 我在 Larvavel sanctum 注销中做错了什么
- java - Java HashMap
- optimization - 为什么这段代码在优化编译时运行得这么快?
- excel - 将多列列表框导出到特定范围