0

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.

Rey
  • 1,393
  • 1
  • 15
  • 24

1 Answers1

0

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');
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52
  • And then what would I put in the actual template? As is as you have it, you'll get an error. Did you mean to put "this.myDate" within the body of the constructor? – Rey Nov 09 '17 at 23:58
  • You still have this.staff.profile.hireDate sitting outside of the body of the constructor. This will cause an error. – Rey Nov 10 '17 at 17:21