Saturday, June 23, 2018

Format DateTime with a Custom DateTime Pipe in Angular 2 +

I have explained creating a custom date formatting in angular 2 using pipes in my previous article. In this article, I'm going to create an application with custom DateTime Pipe which can configure the format from one place that will affect to the entire application without find and replace the hard-coded angular default formatting options.

Step 01: Create an Angular App
  $ ng new dateTimeFormatApp

Step 02: Navigate to your dateFormatApp
  $ cd dateTimeFormatApp

Step 03: Create a Pipe using Angular CLI
  $ ng g pipe DateTimeFormat

date-time-format.pipe.ts looks like this:
import { Pipe, PipeTransform } from '@angular/core';
import { DateTimePipe } from '@angular/common';

@Pipe({
  name: 'dateTimeFormat'
})
export class DateFormatPipe extends DatePipe implements PipeTransform {

  private readonly dateTimeFormat = "dd-MM-yyyy HH:mm"; // feel free to move this to a constants.ts file
  transform(value: any, args?: any): any {
    return super.transform(value, this.dateTimeFormat);
  }
}
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Custome DateTimeFormat Pipe Demo';
  date = new Date();
}
app.component.html
Welcome to {{ title }}!
Date: {{date | dateTimeFormat}}

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { DateTimeFormatPipe } from './pipes/date-time-format.pipe';

@NgModule({
  declarations: [AppComponent, DateTimeFormatPipe],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Output

No comments:

Post a Comment