【问题标题】:How to compare dates using ngIf in angular 2 and update the card background accordingly?如何在角度 2 中使用 ngIf 比较日期并相应地更新卡片背景?
【发布时间】:2017-10-07 21:45:20
【问题描述】:

我有“md-grid-list”来在网格中显示卡片。我正在使用“ngFor”循环我的数据数组。如何使用“ngIf”将数组中的每个日期时间元素与给定的日期时间进行比较?如果条件成功,卡片的颜色设置为绿色,如果条件不满足,卡片的颜色设置为不同的颜色。

<md-grid-list cols="4"  rowHeight="250px" gutterSize="20px">
  <md-grid-tile  *ngFor="let data of mydata" >
        <div *ngIf="(data.myDatetime | date:'HH:mm:ss, MMMM dd') < (myCurrentDateTime |date:'HH:mm:ss, MMMM dd')">

      <md-card [style.background]="'red'" [style.minHeight]="'100%'">   
    <md-card-title></md-card-title>
    <md-card-title></md-card-title>
    <md-card-content>
    <h2>
    </h2>
    </md-card-content>  
    </md-card>
        </div>
  </md-grid-tile>
</md-grid-list>

【问题讨论】:

  • 请添加您的作品
  • @AmadouBeye 我没有使用小提琴。我想知道如何在 Angular 2 的 ngFor 中使用 ngIf else。我想根据条件动态更新卡片。
  • @AmadouBeye 实际上,你应该使用 plunker,而不是 jsfiddle

标签: angularjs angular-material angular-directive angular-material2 angularjs-ng-if


【解决方案1】:

JavaScript 使用对象来存储日期值。当你想比较两个日期是否相等时,不要这样做 date1 === date2。这只会告诉你两个变量是否引用同一个对象。

要检查两个日期是否相等,请使用日期对象的 getTime() 方法。像这样:

date1.getTime() == date2.getTime()

请小心,因为任何以秒为单位的差异都将无法匹配日期。

在你的情况下,它将是:

ngIf="data.myDatetime.getTime() < myCurrentDateTime.getTime()"

如果日期格式是 Unix 时间戳:

ngIf="data.myDatetime < myCurrentDateTime"

希望对你有帮助

【讨论】:

  • 日期格式为 Unix 时间戳。例如,这是两个日期 1494315270412 和 1494258011370。如何比较这些日期?
猜你喜欢
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 1970-01-01
相关资源
最近更新 更多