0

Problem: I have an external library in my angular app with components. Some of this components use Angular DatePipe internally to transform dates in the 'shortDate' format. I don't really have the option to use any other component or implement a custom one as it's a requirement for the client to use that specific library. But of course they don't want 'shortDate' format aswell.

I tried extendeding the built-in Angular DatePipe. As follows:

import { DatePipe } from '@angular/common';
import { Inject, LOCALE_ID, Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'date'
})
export class DateExtendedPipe extends DatePipe implements PipeTransform {

  static readonly DEFAULT_FORMAT = 'dd/MM/yyyy';
  
  constructor(@Inject(LOCALE_ID) locale: string) {
    super(locale)
  }

  transform(value: Date | string | number, format?: string, timezone?: string, locale?: string): string | null;
  transform(value: null | undefined, format?: string, timezone?: string, locale?: string): null;
  transform(value: Date | string | number | null | undefined, format?: string, timezone?: string, locale?: string): string | null {
    console.log('date format');
    
    const ghibFormat = format && format !== 'shortDate' ? format : DateExtendedPipe.DEFAULT_FORMAT;
    return super.transform(value, ghibFormat, timezone, locale);
  }

}

This works for any custom-component that i have currently implemented in my app. Whenever i use 'my_var | date' it triggers my extended pipe instead of Angular's.

As for node_modules components it still triggers the default Angular DatePipe instead of my extended one. I assume this has to do with the way the angular architecture is built and the compiler compiles node_modules first. Not entirely sure. Just wanted to see if anyone came accross a similiar problem, and if there's any magical solution. Thank you!

1 Answers1

0

You just have to set the correct provider:

  providers: [{
    provide: DatePipe,
    useClass: MyDatePipe
  }]

This will provide MyDatePipe to everyone wanting DatePipe.

Apparently this is deprecated, and now you should simply add it in your App module declarations. See answer Override Angular default date pipe

Salketer
  • 14,263
  • 2
  • 30
  • 58