css - Angular ngClass mat-list-item 添加条件以应用背景色

标签 css angular angular-material background-color

我一直在尝试使用 ngClass 将背景颜色应用于 mat-list 和 mat-list-item。如果条件为真,背景颜色为黄色,否则保持正常的白色。当我只是应用常规

style="background-color:yellow" 

在我的 html 代码中,所有 mat-list-item 单元格的背景色都是黄色。

我改了下面的,但是不行

[ngClass]="myData.hasAlert ? 'highlight-color' : 'normal-color'"
[ngClass]="{'highlight-color' : myData.hasAlert }"

作为测试,我什至尝试了 ng-style="{ highlight : myData.hasAlert }"但没有任何效果。

这是我的代码

<div class="ng-container" >
    <mat-list [ngClass]="test.IsNotRedAlert ? 'my-list-black-font' : 'my-list-red-font'"> 
        <!-- insert the subtotals-->
        <mat-list-item 
          fxLayoutAlign="end" 
          class="metric-possition"
          *ngFor="let myData of AllData"
          class="background-color:yellow">
            {{myData.balance}}</span>
        </mat-list-item>
    </mat-list>
</div>

首先,我将 css 类添加到 mat-list ngClass 中,但它会将 mat-list 下的所有子 mat-list-item 更改为黄色背景色。如果 myData.hasAlert 的条件为真,我只需要将背景应用于特定的 mat-list-item 单元格。

我尝试了以下 css

.highlight .mat-list-item {
  background-color: yellow;
}

.highlight   {
  background-color: yellow;
}

任何帮助表示赞赏。谢谢。

最佳答案

使用 ngClass,根据 the documentation,这是您应该使用的正确语法:

<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>

所以在你的情况下,那将是:

<mat-list-item [ngClass]="{'yellow-background': myData.hasAlert}">

在你的 CSS 文件中:

.yellow-background {
    background-color: yellow;
}

关于css - Angular ngClass mat-list-item 添加条件以应用背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55396004/

相关文章:

javascript - 改变 HTML 元素的可见性

angular - 为什么我的主题可观察订阅者在 Angular 中多次调用?

angular - 来自 Angular 4 的 HttpInterceptor 单元测试

angular - 具有静态数据的 Material Design 数据表布局

html - 当父项具有相对高度时,如何在子项 div 上强制滚动条?

html - Div 应该居中,但事实并非如此?

css - 使用 CSS 的多元素翻转

css - Angular CLI 没有 LESS/SASS 的源映射

javascript - 当进行有效的单选选择或文本输入时,聚焦于下一个 div

angular - Material Design Lite 和 Angular Material Design 有什么区别?