2017-11-10 48 views
0

我想在我的Angular應用程序中使用日期管道以在輸入中的模板中使用它時正確解析出日期管道。最初,格式化日期之前,代碼是這樣的:獲取日期格式化並在Angular 2中打印到屏幕App

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

我的日期管得到最接近的是這樣的:

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

但是,打印的看法是這樣的(從字面上此):

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

現在,你會發現,正確格式的日期是存在的(和日期轉化成功發生,使它這樣:

3/18/2014 

但是,我不想休息(顯然)。我該如何重新修改這裏的語法以便獲得打印日期?我盯着它,並嘗試了一些調整,但迄今還沒有得到它的工作。

+1

value ='{{staff.profile.hireDate | date:'shortDate'}}'在你的輸入標籤中 – getbuckts

回答

0

您可以使用typcript和ngModelChanged屬性中的get和set函數在設置後修改ngModel

組件模板:

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

組件類:

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) { 
    } 
} 

輸入的值將被設置,只要輸入的變化,所以它可能會導致UX問題,因爲用戶將無法輸入他的首選日期。解決方法是每當用戶輸入日期時調用日期更改函數。 (例如,通過點擊按鈕)。

我相信set和get函數只能用於類變量,在你的情況下你有一個對象屬性。如下所示修改設置功能將起作用。

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

我還添加了一個plunkr here