0
votes

I am trying to transform the way some dates are displayed in my Angular 2 app. In my case, using the date pipe in the view along with string interpolation is not an option, because my template code looks like this:

<input class="app-input"
    [(ngModel)]="staff.profile.hireDate" placeholder="None"
    [field-status]="getPropertyStatus('profile.hireDate')"/>

A commenter suggested I try handling the transformation of the date in the component, before passing it to the view. This is what he wrote:

You can do this in your component.

import { DatePipe } from '@angular/common'; then either add it to the providers array in component or in your ngModule.

In your component you inject this in your constructor:

constructor(private myDatePipe: DatePipe) {} and modify your variable property:

this.staff.profile.hireDate = this.myDatePipe.transform(new Date(this.staff.profile.hireDate));

This sounds like the perfect solution. However, I'm still unclear on the exact implementation. I have imported DatePipe and have defined a local instance in the constructor. But where does this next part go:

this.staff.profile.hireDate = this.myDatePipe.transform(new Date(this.staff.profile.hireDate));

I tried putting it in the body of the constructor, but no go.

So I'm still a little unclear as to where this goes, and if I need to also change the code in the view after that.

Any clarity would be much appreciated.

1

1 Answers

0
votes

use DatePipe that way

NgModule({
  providers: [DatePipe]
})

and inside your component:

import { DatePipe } from '@angular/common';
...
constructor(private datePipe: DatePipe) {}
...
this.staff.profile.hireDate= this.datePipe.transform(this.staff.profile.hireDate, 'dd-MM-yy');