gpt4 book ai didi

javascript - 仅当日期是今天时才使用 *ngIf 申请类(class)

转载 作者:行者123 更新时间:2023-11-30 11:38:39 24 4
gpt4 key购买 nike

这是我试过的。

HTML:

<span *ngIf="!today" class="not-today">{{operation}}</span>
<span *ngIf="today" class="today">{{operation}}</span>

组件:

 private today: any;
this.today = new Date().getTime();

只有在今天(.not-today 到不是“今天”的跨度)我才需要应用 span.today 类,这样我使用 .not-today 类获取所有跨度。我怎样才能做到这一点?

谢谢。

最佳答案

Assuming your operation variable is an object and that object has a property of type time and depending on what that time is relevant to the present time you want to assign specific classes to your span element.

有两种方法可以做到这一点:

ng类

一种是通过让方法返回相关类来利用 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 适用于只有一个类的情况。

关于javascript - 仅当日期是今天时才使用 *ngIf 申请类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43453436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com