【问题标题】:Angular ngClass with condition [duplicate]带有条件的Angular ngClass [重复]
【发布时间】:2021-07-19 22:25:49
【问题描述】:

我从 JSON 文件而不是数据库中获取数据。我正在尝试根据 JSON 中的状态值为图标赋予颜色,例如 [如果绿色? class1:class2] 下面是我的代码。

我的 HTML 文件

   <ng-container matColumnDef="status" [ngClass] = "{'color1': row.status === 
        'GREEN', 'color2': row.status === 'RED'}">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>Status</th>
        <td mat-cell *matCellDef="let row" class="color1">{{row.status}}</td>
        <td mat-cell *matCellDef="let row" class="color2">{{row.status}}</td>
    </ng-container>

下面是我的 JSON 文件

    data:[
          {
           "name": "xyz",
           "address": "post",
           "status": "GREEN"
          },
          {
           "name": "xyz1",
           "address": "post1",
           "status": "RED"
           }
         ],
       "count" : 2
}

这是我的 CSS

.color1{
  color: green;
}

.color2{
  color: red;
}

** 我无法更改状态图标的颜色。我得到了这个错误**

ERROR TypeError: Cannot read property 'status' of undefined

【问题讨论】:

标签: html css angular


【解决方案1】:

ngClass 接收对象键值,键是可能的类,值是应用键的条件

您可以对此类的每个可能值使用静态检查。

 <td mat-cell *matCellDef="let row" class="color1"
     [ngClass]="{
     'green': row.status === 'GREEN',
     'red': row.status === 'GREEN'">{{row.status}}</td>


相同想法的其他选择

<td mat-cell *matCellDef="let row"
[class.red] = "row.status === 'RED'"
[class.green] = "row.status === 'GREEN'" >
{{row.status}}
</td>

另一种方法是使用 map objetc 在您的 ts 中定义类并像这样从 html 访问一次 打字稿文件

mapClass = {
  'GREEN': 'green',
  'RED': 'red' 
}

和html

 <td mat-cell *matCellDef="let row" class="{{mapClass[row.status]}}">{{row.status}}</td>

如果您的可能类值经常更改,则最后一个更好,使用 mapClass 您只需添加新的可能值并定义 css 类,html 保持不变。

编辑: 我认为您编辑了原始问题,我回答了原始问题。 我认为您当前的错误是因为您正在尝试将 ngCLass 与 ngcontainer 一起使用,请尝试在 td 中使用 ngClass。 我看到您在具有不同类的容器内显示双 td,而没有 ngIf。如果我理解正确,那么使用这种方式你应该使用 ngIf 来显示行状态一次。 无论如何,请查看我之前的答案,希望对您有所帮助

【讨论】:

  • 非常感谢它现在可以工作了.....
猜你喜欢
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 2018-04-01
  • 1970-01-01
  • 2017-12-02
相关资源
最近更新 更多