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

Angular ngClass mat-list-item adding condition to apply 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 class 添加到 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;
}

您的 class 声明无效。

更改为以下代码

<div class="ng-container">

  <mat-list>
    <!-- insert the subtotals-->
    <mat-list-item *ngFor="let myData of allData"
                   [ngClass]="{'highlight':myData.hasAlert}">
      {{myData.balance}}
    </mat-list-item>
  </mat-list>
</div>

而不是 ngClass,您可以使用以下语法:

 <mat-list [class.my-list-black-font]="test.IsNotRedAlert">