【问题标题】:angular - changing the icon colour when clicked角度 - 单击时更改图标颜色
【发布时间】:2019-03-13 10:36:04
【问题描述】:

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

<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";

}

我需要做什么来改变其中的一个?

【问题讨论】:

  • 在 ngfor 中,您所有的按钮 id 都相同

标签: angular typescript material-design


【解决方案1】:

您当前的解决方案不起作用,因为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] 以“Angular 方式”处理此问题,这使我们能够定义一个简单的表达式来在白色和蓝色之间切换。

【讨论】:

  • 感谢您的回答。它工作得很好。另一个问题,有没有办法“取消选择”它?意味着图标的颜色恢复到以前的颜色。
  • 在您的addToSummary 方法中只需执行:content.isSelected = !content.isSelected。这会将布尔值从 true 翻转为 false,反之亦然。
【解决方案2】:

你也可以这样试试

 <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";
}

【讨论】:

  • 我个人建议不要在 Angular 中使用 document.getElementBy... 方法。 Angular 完全有能力在不使用这些方法的情况下处理 OP 的问题。
【解决方案3】:

渲染器可用于操作 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');
}

【讨论】:

  • 请不要这样做。在使用 Angular 时,使用查询选择器确实应该是最后的努力。 OP 的问题是 Angular 无需任何查询选择器即可解决的经典问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 2020-01-21
  • 2022-01-03
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2015-10-17
相关资源
最近更新 更多