这是我尝试过的。
HTML:
<span *ngIf="!today" class="not-today">{{operation}}</span>
<span *ngIf="today" class="today">{{operation}}</span>
组件:
private today: any;
this.today = new Date().getTime();
我需要应用span.today
课程,只有今天(.not-today
适用于今天不是&#39;)这样我才能获得所有课程跨度为.not-today
级。我怎样才能做到这一点?
感谢。
答案 0 :(得分:2)
假设您的
operation
变量是一个对象而该对象有一个 类型时间的属性,取决于与时间相关的内容 您希望为跨度指定特定类的当前时间 元件。
有两种方法可以做到这一点:
一种方法是通过让方法返回相关的类来利用ngClass
属性,即:
getClassFromDate(date: Date) {
let match = date.getTime(); // convert date to number
let today = new Date().setHours(0,0,0,0); // get present day as number
let day = (n) => today + (86400000 * n); // assuming all days are 86400000 milliseconds, then add or remove days from today
if (match >= day(1) && match < day(2))
return 'tomorrow';
else if (match >= today && match < day(1))
return 'today';
else if (match < today && match > day(-2))
return 'yesterday';
else
return 'other';
}
然后在你的模板中:
<span [ngClass]="getClassFromDate(operation.date)">{{operation.text}}</span>
然后当然包括样式表中的相关类:
.tomorrow {...}
.today {...}
.yesterday {...}
.other {...}
您的课程也可以这样添加:
<span [class.tomorrow]="tomorrow" [class.today]="today" [class.yesterday]="yesterday" [class.other]="!tomorrow && !today && !yesterday">{{operation}}</span>
在这种情况下,它需要boolean
并在表达式等于true时应用该类。但请注意,您需要重写逻辑以了解日期的处理方式。
您可以详细了解两个here之间的差异。作为一般经验法则,ngClass
用于当您有多个应该添加的类时,class.className
适用于只有一个类的情况。
答案 1 :(得分:1)
您可以通过以下方式实现
假设&#34;操作&#34;作为字符串&amp; &#34; todayDate&#34;作为当前日期((即)今天的实际情况日期来自数据库)。
代码看这个
<强> HTML:强>
<span [ngClass]="(getTodayClass()=== 'today') ? 'today' : 'not-today'">{{operation}}</span>
<强> CSS:强>
<style>
.today {
background-color:red;
}
.not-today {
background-color:green;
}
<强>组件:强>
//declaraion
todayDate: Date;
operation: string;
private sameDays(d1: Date, d2: Date) {
return d1.getUTCFullYear() == d2.getUTCFullYear() &&
d1.getUTCMonth() == d2.getUTCMonth() &&
d1.getUTCDate() == d2.getUTCDate(); //using UTC methods ensures that two equivalent days in different timezones matching
}
getTodayClass() {
//variable assign
this.todayDate = new Date; //this date get from database
this.operation = "Monday";
//check condition for database time and current time with help of UTC
if (this.sameDays(this.todayDate, new Date)) {
return 'today';
} else {
return 'not-today';
}
}
希望这对您的期望有所帮助