角度-单击时更改图标颜色

时间:2019-03-13 10:36:04

标签: angular typescript material-design

我目前有一个显示项目列表的表格。每个项目旁边都有一个图标。我要做的是单击它们的图标,它将改变其颜色。现在,当我单击任何图标时,它只会更改第一个图标的颜色。

<table class="table table-borderless" style="background-color: #CCE4E9">
    <tbody>
        <tr *ngFor="let content of acts">
            <td style="font-size: 14px;" *ngIf="content.status == 2;">{{content.description}}
            </td>
            <td>
                <button id="addToSummary" class="mdc-icon-button material-icons" style="color: #FFFFFF;"
                    (click)="addToSummary()">grade</button>
            </td>
        </tr>
    </tbody>
</table>

addToSummary(){
  document.getElementById("addToSummary").style.color = "#3DA2DA";

}

screenshot

我该怎么做才能更改其中之一?

3 个答案:

答案 0 :(得分:2)

您当前的解决方案无效,因为getElementById仅返回具有给定ID的单个(第一个找到的)元素。除了执行这种DOM查询外,绝对不是Angular方式。

相反,您需要将按钮定义更改为以下内容:

<button class="mdc-icon-button material-icons" [style.color]="content.isSelected ? '#3DA2DA' : 'FFFFFF'" (click)="addToSummary(content)">grade</button>

我们还更改了addToSummary方法,使其看起来像这样:

addToSummary(content){
    content.isSelected = true;
}

所以基本思想是这样的:

  • acts数组中的每个元素都有一个isSelected属性
  • 如果将此属性设置为true,则星标为蓝色
  • addToSummary方法中,我们将isSelected属性设置为true
  • 我们通过使用[style.color]来处理“角度方式”,这使我们可以定义一个简单的表达式来在白色和蓝色之间切换。

答案 1 :(得分:0)

您也可以这样尝试

 <table class="table table-borderless" style="background-color: #CCE4E9">
   <tbody>
        <tr *ngFor="let content of acts; let i = index;">
           <td style="font-size: 14px;" *ngIf="content.status == 2;"> 
              {{content.description}}
           </td>
           <td>
               <button id="addToSummary" [ngClass]="['addToSummary', i]" class="mdc-icon-button material-icons" style="color: #FFFFFF;"
                (click)="addToSummary(i)">grade</button>
           </td>
        </tr>
  </tbody>
</table>

addToSummary(i){
     let className = "addToSummary " + i;
     document.getElementByClassName(className).style.color = "#3DA2DA";
}

答案 2 :(得分:0)

渲染器可用于操作DOM

import { ElementRef, Renderer2} from '@angular/core';

constructor(private elRef: ElementRef, private renderer: Renderer2) { }

addToSummary() {
    let elm = this.elRef.nativeElement.querySelector('#addToSummary');
    this.renderer.setStyle(elm, 'color', '#3DA2DA');
}
相关问题