【问题标题】:Set different colors each row index in html table using Angular 4使用Angular 4在html表中为每个行索引设置不同的颜色
【发布时间】:2018-07-30 14:10:13
【问题描述】:

每次单击表格外的按钮时,我想以编程方式为选定的行设置不同的颜色。我正在使用最新版本的 angular。

我知道如何使用 css 设置行颜色,但不知道如何在 typescript 中以编程方式影响 css 类。

.ui-table .ui-table-tbody > tr:nth-child(1) {
    background-color: #2DA449; 
}

有没有办法编辑 css 类以在 typescript 中设置子索引和 b-color?

【问题讨论】:

标签: angular typescript


【解决方案1】:

打字稿

export class MyComponent{
    items:any[];
    changeColors(){
    // I'm just selecting the first row for this example but you have to define your own logic 
    this.items[0].color ="#ddd";
    }
}

HTML

<button (click)="changeColors()">Change colors<button/>
<table>
  <tr *ngFor="let item in items;let i=index" [style.color]="item.color">
    ...
  </tr>
</table>

更多文档可以找到https://angular.io/guide/template-syntax#binding-targets

【讨论】:

  • 很好的例子,但是如何在 chsngeColors() 方法中设置颜色而不是给 tr 标签一个静态的?
  • 啊,我误解了你的问题,请更新我的答案。
【解决方案2】:

您只需要ngClass

<td [ngClass]="{'selected': checkSelected(i)}"> // checkSelected should return boolean

WORKING DEMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多