Add Pipe

We will add a calendar pipe, to transfer Sun Sep 25 2016 19:32:32 GMT-0400 (EDT) to human friendly text. We will use updateLocale from Moment.js.

To install Moment.js and its related typing file, run the following codes in the terminal:

npm install moment --save
npm install @types/moment --save-dev

Add the file

src/app/shared/pipes/calendar.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
  name: 'calendar'
})
export class CalendarPipe implements PipeTransform {
  transform(time: Date): string {
    if (!time) return '';

    // http://momentjs.com/docs/#/customization/calendar/
    moment.updateLocale('en', {
      calendar : {
        lastWeek : 'dddd',
        lastDay : '[Yesterday]',
        sameDay : 'LT',

        sameElse : 'L'
      }
    });

    return moment(time).calendar();
  }
}

Add CalendarPipe in the declarations of

src/app/app.module.ts

// ...
import { CalendarPipe } from './shared/pipes/calendar.pipe';

@NgModule({
  // ...
  declarations: [
    // ...
    CalendarPipe
  ],
  // ...
})
export class AppModule {}

In the file src/app/chat/components/chat.component.ts, change

{{message.timestamp}}

to

{{message.timestamp | calendar}}

Your app should look like this now:


Run the live example for this part.

Note in the plunker, when we import Moment.js, we use import moment from 'moment';, however in your app generated by Angular-CLI, you should use import * as moment from 'moment';.

This is because Angular-CLI uses Webpack as build system, while plunker uses SystemJS as build system.

results matching ""

    No results matching ""