【问题标题】:ngClass on an angular mat table row角度垫表行上的 ngClass
【发布时间】:2021-09-25 14:12:02
【问题描述】:

我想使用角度选择的选择选项来更改角度材料表的特定行的 css 类。

我的选择完美运行,我可以在选择时为地球提供“selected=true”属性。 (所有其他设置为假)。现在我想更改特定行的 css 类(红色边框),其中对象具有“选定”属性 = true。

我的 html 看起来像这样:

<table mat-table [dataSource]="planets" [trackBy]="trackById" class="mat-elevation-z8" id="planetList">

//所有 ng 容器

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row [ngClass]="{'selectedPlanet': planet.selected === 'true'}" *matRowDef="let row; columns: displayedColumns;"></tr>
CSS:
.selectedPlanet {border-color: red;}

但我有一个问题,我的控制台抛出一个错误,例如“ctx_r7.planet 未定义”。 我不知道如何在 mat 表上使用 ngClass 来更改行。 有谁知道,我该如何解决这个问题?

【问题讨论】:

  • 试试 {'selectedPlanet': planet && planet.selected === 'true'}

标签: html css angular typescript mat-table


【解决方案1】:

你需要一个安全的导航,因为你的星球是未定义的。

<tr mat-row [ngClass]="{'selectedPlanet': planet?.selected === 'true'}" *matRowDef="let row; columns: displayedColumns;"></tr>

您没有定义行星我假设条目行已选择属性,因此使用行属性访问任何属性

<tr mat-row [ngClass]="{'selectedPlanet': row?.selected === 'true'}" *matRowDef="let row; columns: displayedColumns;"></tr>

【讨论】:

    【解决方案2】:

    您可以使用 安全导航运算符 吗?在 Angular 模板中确保不会出现此类错误(在读取可能未定义/为空的对象属性时):

    将代码更改为:

    [ngClass]="{'selectedPlanet': planet?.selected === 'true'}"
    

    理想情况下,我们应该确保依赖于某个对象的模板代码应该在对象可用时呈现,通常使用 *ngIf 指令。

    【讨论】:

    • 这只会消除错误。我的主要问题是,我如何告诉表格,检查数据源并搜索正确的行,其中对象具有“selected=true”属性。
    • 在你的课堂上尝试将planet.selected更改为row.selected。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2017-10-13
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    相关资源
    最近更新 更多