覆盖Angular默认日期管道

时间:2019-05-07 10:22:09

标签: angular date-pipe

我需要覆盖默认的Angular 7日期管道格式(mediumshortfullDate等),因为我不想使用两个日期管道(默认值和自定义值),因此我做了以下事情,想知道这样做是一个好主意:

// 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

如果我使用类似{{ someDate | date: 'MM/dd/yyyy' }}之类的东西,它也可以正常工作。

因此,基本上,我想知道是否存在无法正常运行的情况,或者有更好的方法来实现此目标,但是实现方式不同吗?

1 个答案:

答案 0 :(得分:2)

您缺少日期管道中的某些功能。除了formattimezonelocale以外,它还有parameters

可以覆盖默认管道,在该管道中添加“ last”的管道将获得优先权。要覆盖整个应用程序中的角形管道,只需将自定义管道添加到根AppModule的管道数组即可:

@NgModule({
  //...
  pipes: [
    //...
    ExtendDatePipe 
  ]
})
export class AppModule {}

注意:曾经有一个PLATFORM_PIPES常量可以覆盖全局/默认管道,但这是removed

为了提高可读性并保持本地化和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);
  }
}
相关问题