【问题标题】:Angular conditional class gets overriddenAngular 条件类被覆盖
【发布时间】:2019-06-07 16:26:03
【问题描述】:

我有 2 个 CSS 类,date-today 有条件地应用于一个元素,但它不起作用,因为日期会覆盖它。

.date-today {
    color: red;
}

.date {
    color: green;
}

组件:

[ngClass]="{ 'date-today': date.isToday() }"

如何让date-today 类覆盖date

【问题讨论】:

  • 你能提供你用过的完整的html代码以及你的带有date.isToday()的ts吗??
  • 你为什么不直接删除破折号并将类写为dateToday?这样它就不应该覆盖它......

标签: html angular css


【解决方案1】:

更改css规则的顺序以防止覆盖(它调用specificty

/*date first*/
.date {
    color: green;
}
/*date-today second*/
.date-today {
    color: red;
}
<div class="date date-today">
date
</div>

查看规则顺序发生变化时会发生什么:

.date-today {
    color: red;
}
.date {
    color: green;
}
<div class="date date-today">
date
</div>

【讨论】:

    【解决方案2】:

    您可以将color: red; 更改为color: red!important;,但也许您可以移动您的date 类设置到[ngClass] 并按如下顺序放置

    [ngClass]="{ 
        'date': !date.isToday(),
        'date date-today': date.isToday()
    }"
    

    【讨论】:

      【解决方案3】:

      你可以用这个

      <p [class.date]="!today" [class.date-today]="today">
        Start editing to see some magic happen :)
      </p>
      <button (click)="today = true">today</button>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-02-02
        • 2018-08-04
        • 2017-08-26
        • 1970-01-01
        • 2022-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多