Mar*_*nov 10 date-pipe angular
我需要覆盖默认的 Angular 7 日期管道格式(medium、short、fullDate等),因为我不想使用两个日期管道(默认一个和自定义一个),所以我做了以下并想知道是一个这样做的好主意:
// extend-date.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'date'
})
export class ExtendDatePipe extends DatePipe implements PipeTransform {
constructor() {
super('en-US');
this.customDateFormats = {
medium: '...',
short: '...',
fullDate: '...',
longDate: '...',
mediumDate: '...',
shortDate: '...',
mediumTime: '...',
shortTime: '...'
};
}
transform(value: any, args?: any): any {
switch (args) {
case 'medium':
return super.transform(value, this.customDateFormats.medium);
case 'short':
return super.transform(value, this.customDateFormats.short);
case 'fullDate':
return super.transform(value, this.customDateFormats.fullDate);
case 'longDate':
return super.transform(value, this.customDateFormats.longDate);
case 'mediumDate':
return super.transform(value, this.customDateFormats.mediumDate);
case 'shortDate':
return super.transform(value, this.customDateFormats.shortDate);
case 'mediumTime':
return super.transform(value, this.customDateFormats.mediumTime);
case 'shortTime':
return super.transform(value, this.customDateFormats.shortTime);
default:
return super.transform(value, args);
}
}
}
// app.component.html
{{ someDate | date: 'medium' }} // The custom format will be displayed
Run Code Online (Sandbox Code Playgroud)
如果我使用类似的东西,{{ someDate | date: 'MM/dd/yyyy' }}它也会起作用。
所以基本上,我想知道是否存在这种情况无法正常工作的情况,或者可能有更好的方法来实现这一目标,但实现方式不同?
Pie*_*Duc 10
您错过了日期管道中的某些功能。它有此外format,也timezone和locale作为参数。
覆盖默认管道是可能的,其中“最后”添加的管道将获得优先级。要覆盖整个应用程序中的角度管道,只需将自定义管道添加到根 AppModule 的声明数组中即可:
@NgModule({
//...
declarations: [
//...
ExtendDatePipe
]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
注意:曾经有一个PLATFORM_PIPES常量来覆盖全局/默认管道,但这已被删除
为了可读性并保持本地化和 i18n 的可能性,我只是将其更改为这个。:
@Pipe({
name: 'date'
})
export class ExtendDatePipe extends DatePipe implements PipeTransform {
readonly customFormats = {
medium: 'xxx',
short: 'xxx',
// ...
};
constructor(@Inject(LOCALE_ID) locale: string) {
super(locale);
}
transform(value: any, format = 'mediumDate', timezone?: string, locale?: string): string {
format = this.customFormats[format] || format;
return super.transform(value, format, timezone, locale);
}
}
Run Code Online (Sandbox Code Playgroud)
从 Angular 15 开始,您可以使用 DATE_PIPE_DEFAULT_OPTIONS 注入令牌覆盖默认的日期管道配置(格式、时区等)。它在你的 app.module.ts 中的工作方式如下:
providers: [
{provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {dateFormat: 'mm/DD/yy'}}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4055 次 |
| 最近记录: |