首页 > 解决方案 > 如何使用 Angular 创建“当前日期”按钮

问题描述

我目前正在构建一个具有前一天、当天和第二天按钮的日程安排应用程序。我将如何创建当前日期按钮?

HTML 文件

    <button type="button" (click)="previousDay()" >Left</button> 
    <br>
    <h2>{{ currentDay }}</h2>
    <br>
    <button type="button" (click)="nextDay()" >Right</button>
    <br>
    <button type="button" (click)="currentDay()" >Current Day</button>
    <br>
</div>

打字稿文件:

export class DayViewComponent implements OnInit {

  events: any[];
  currentDay: Date;
  modalActive: boolean = false;

  previousDay() {
    this.currentDay.setDate(this.currentDay.getDate()-1);
  }

  nextDay() {
    this.currentDay.setDate(this.currentDay.getDate()+1);
  } 

  currentDay(){

}
}

标签: angulartypescriptbutton

解决方案


我会小心命名你的函数。currentDay必须是日期函数是令人困惑的。在你的函数前面加上'set'怎么样?

    setCurrentDay() {
      this.currentDay = new Date()
    }

推荐阅读