2017-04-13 96 views
1

這是我今天的日期功能:如何在Angular2中應用日期?

public static todaysDate(month: number): string { 
     let day = new Date().getDate(); 
     let year = new Date().getFullYear(); 
     return "<span>" + day + ", " + "</span>" + year; 
    } 

,這是爲明天的日期:

public static tomorrowsDate(month: number): string { 
      let day = new Date().getDate() + 1; 
      let year = new Date().getFullYear(); 
      return "<span>" + day + ", " + "</span>" + year; 
     } 

在我的HTML:

<ul class="text-left"> 
       <li><img src="../left.png"/></li> 
       <li><span [innerHTML]="date"></span></li> 
       <li><img src="../images/right.png"/></li> 
      </ul> 

我使用[innerHTML]呈現HTML <span></span>標籤。

這是我的組件:

this.date = Date.todaysDate(this.month); 
this.dateTomorrow = Date.tomorrowsDate(this.month); 

如何我可以申請明天的日期和昨天的日期right.png和left.png形象點擊?

回答

2

這似乎更好地爲你的函數返回一個日期和使用管內插字符串格式化所需的日期格式。

就像這樣{{date |日期}}

下面是一個例子的plunker:https://plnkr.co/edit/amip8h2pZMxeM7fi7yAZ?p=preview

我使用的按鈕,因爲我沒有你的圖片,但代碼應該基本上是相同的。

<ul class="text-left"> 
     <li><button (click)="todaysDate(3)">left</button></li> 
     <li>{{date | date}}</li> 
     <li><button (click)="tomorrowsDate(3)">right</button></li> 
    </ul> 

和組件的功能:

export class App { 
    name:string; 
    date: date; 
    constructor() { 
     this.name = `Angular! v${VERSION.full}` 
    } 

    todaysDate(month: number): void { 
    let day = new Date().getDate(); 
    let year = new Date().getFullYear(); 
    this.date = new Date(year, month, day); 

    } 

    tomorrowsDate(month: number): void { 
     let day = new Date().getDate() + 1; 
     let year = new Date().getFullYear(); 
     this.date = new Date(year, month, day); 
    } 
} 
+0

函數中的'3'是什麼? – tholo

+0

你的功能都以一個月爲參數......所以我認爲我們需要通過月份號碼? – DeborahK

+0

如果你不需要在一個月內通過,那麼刪除3並更改功能不需要一個月。 – DeborahK

2

您需要爲每個按鈕綁定click事件。在您的點擊事件中,更新您的date變量。所以,你的HTML會像

<ul class="text-left"> 
    <li><img ng-click="yesterdayDate()" src="../left.png"/></li> 
    <li><span>{{date}}</span></li> 
    <li><img ng-click="tomorrowDate()"src="../images/right.png"/></li> 
</ul> 
+0

我可以綁定多個點擊事件?這是Angular2,而不是AngularJS。 ) – tholo

+0

你是什麼意思多個點擊事件?如果是angular2,請更新您的問題標籤 –