0

I am trying to get the date pipe I'm using in my Angular app to parse out correctly when using it in the template within an input. Initially, before formatting the date, the code looked like this:

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

The closest I've gotten with the date pipe is this:

<input class="app-input"
{{ staff.profile.hireDate | date:'shortDate' }} placeholder="None"
[field-status]="getPropertyStatus('profile.hireDate')"/>

But what that prints to the view is this (literally this):

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

Now, you'll notice that the correctly formatted date is there (and the date transformation is happening successfully, to make it this:

3/18/2014

However, I don't want the rest (obviously). How can I rework the syntax here so as to get just the date to print? I've stared at it and tried a few tweaks, but as of yet haven't been able to get it to work.

Rey
  • 1,393
  • 1
  • 15
  • 24

1 Answers1

0

You can use the get and set functions in typescript and ngModelChanged property to modify the ngModel after it has been set.

Component Template :

<input class="app-input" [(ngModel)]="hireDate" (ngModelChange)="dateChanged($event)"/>

Component Class :

import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <button (click)="setDate()">Set Date</button>
      <input class="app-input" readonly="true" [(ngModel)]="hireDate" (ngModelChange)="dateChanged($event)" placeholder="None"/>
    </div> 
  `,
})
export class App {
  name:string;
  staff: any;
  myDate: any;
  private _hireDate;

  dateChanged(value) {
    this.hireDate = this.datePipe.transform(value, 'shortDate');
  }

  set hireDate(value) {
    this._hireDate = this.datePipe.transform(value, 'shortDate');
  }

  get hireDate() {
    return this._hireDate;
  }

  setDate() {
    this.hireDate = '10-03-1993';
  }

  constructor(private datePipe: DatePipe) {
  }
}

The value of the input will be set whenever the input changes, so it might cause a UX issue, as the user would not be able to enter his prefered date. A workaround would be to call the date changed function whenever the user has entered his date. (For eg. via a button click).

I believe the set and get functions work only for class variables, in your case you have a object property. Modifying the set function as shown below would work.

  set hireDate(value) {
    this._hireDate = this.datePipe.transform(value, 'shortDate');
    this.staff.profile.hireDate = this._hireDate;
  }

I have also added a plunkr here.

Midhun Darvin
  • 1,236
  • 14
  • 24