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

时间:2019-03-28 11:04:36

标签: css angular background-color material

我一直在尝试将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-item更改为mat-list下的黄色背景色。如果myData.hasAlert的条件为true,则只需将背景应用于某些mat-list-item单元。

我尝试了以下CSS

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

.highlight   {
  background-color: yellow;
}

感谢您的帮助。谢谢。

3 个答案:

答案 0 :(得分:1)

使用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;
}

答案 1 :(得分:0)

您的课程声明无效。

更改为以下代码

<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>

答案 2 :(得分:0)

您可以使用以下语法代替ngClass

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