首页 > 解决方案 > Angular HTML - 基于布尔值更改表格单元格背景颜色

问题描述

尝试使用 Angular ng-class 设置表格单元格背景颜色。我正在关注这些帖子的片段:

我已将样式放入 app.component.scss 文件中:

.routeRed {
  background-color: red; 
}

.routeGreen {
  background-color: green;
}

我正在使用标准 Angular 加载 app.component.scss 文件:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})

我对 app.component.html 进行了如下编码: <table> 确实位于 Angular Material mat-tab 中,但我不认为这会阻止任何 scss 样式,至少我没有找到任何说材料可以防止这种情况。

<table border="1" class="table" id="idTableCamelRoutes" matSort
    (matSortChange)="sortRoutes($event)" style="width: 100%">
    <thead>
        <tr>
            <th mat-sort-header="routeId">Route Id</th>
            ...Removed for brevity...
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of applicationState.camelRoutes">
            <td>{{ item.routeId }}</td>
            <td>{{ item.routeStatus }}</td>
            <td ng-class="{'routeRed' : !(item.routeRunning), 'routeGreen': item.routeRunning}">{{item.routeRunning}}</td>
            <td>

ngFor 只是遍历 CamelRouteBean 对象的集合:

export class CamelRouteBean {
  routeId: string;
  routeStatus: string;
  routeRunning?: boolean;
  description?: string;
}

所以,我所要做的就是对 ng 类使用 item.routeRunning (一个布尔值)......我还验证了 item.routeRunning 被设置为 true 或 false 就好了。我验证了 app.component.scss 也正在加载。但无论我尝试什么,表格单元格的背景颜色都不会从白色改变。当我在 Chrome 中检查元素时,我没有看到任何样式都应用于表格单元格。

我错过了什么?

蒂亚阿迪姆

标签: htmlcssangular

解决方案


我想你可以像下面这样:

<div
  [ngClass]="{
  'routeGreen': item.routeRunning,
  'routeRed': !item.routeRunning
}"
></div>

推荐阅读