Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend angular2 DatePipe

Up to angular2.beta15 (including) the following code was working fine:

@Pipe({
  name: 'isoDate'
})
export class ISODatePipe extends DatePipe implements PipeTransform {
  transform(isoDate: string, args: any[]): string {
    return super.transform(new Date(isoDate), args);
  }
}

On RC1 its not working anymore, even after I adjusted pipes syntax:

@Pipe({
  name: 'isoDate'
})
export class ISODatePipe extends DatePipe implements PipeTransform {
  transform(isoDate: string, pattern?: string): string {
    const date = new Date(isoDate);
    return super.transform(date, pattern);
  }
}

The message i see in the browser is following: The pipe 'isoDate' could not be found.

If I remove the extends part and return some string - it works again.

What has changed?

P.S.

Currently changed it to

@Pipe({ name: 'isoDate' })
export class ISODatePipe implements PipeTransform {
  private datePipe: DatePipe = new DatePipe();

  transform(isoDate: string, pattern?: string): string {
    const date = new Date(isoDate);
    return this.datePipe.transform(date, pattern);
  }
}

It works, but looks a bit strange.

like image 924
ValeriiVasin Avatar asked May 04 '16 15:05

ValeriiVasin


2 Answers

What has changed?

Apparantely DatePipe class has now constructor

constructor(@Inject(LOCALE_ID) private _locale: string) {} so you can pass LOCALE_ID as parameter:

const datePipe = new DatePipe();

When you compile specifying local ngc --locale=en-US The LOCAL_ID get passed to the DatePipe constructor.

like image 114
Faouzi Oudouh Avatar answered Sep 21 '22 18:09

Faouzi Oudouh


extended DatePipe

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

@Pipe({
  name: 'myDate',
})
export class MyDatePipe extends DatePipe implements PipeTransform {
  constructor(@Inject(LOCALE_ID) locale: string) {
    super(locale);
  }

  transform(value: any, format?: string, timezone?: string, locale?: string): string {
    const formattedDate = super.transform(value, format, timezone, locale);
    // do other formatting and return the value
  }
}

html

<div>{{ someDate | myDate: 'MMM d' }}</div>
like image 40
AngularBoy Avatar answered Sep 24 '22 18:09

AngularBoy