如何在单击按钮时删除样式

How to remove style on click of a button

我有一个按钮在 ngFor 循环中。我是这样设计的。

<div *ngFor="let component of componentList;let index =index">
    <button type="button" id='Button{{index}}' name='Button{{index}}' class="device_name_button"  [ngClass]="{'greencolorstyle':component.status=='Available', 'redcolorstyle': component.status=='Faulted', 'graycolorstyle':component.status=='Unavailable','myClass':isClicked==true}" (click)="selectComponent($event,component.components);" > {{component.name}} </button>
</div>

我正在使用点击事件处理程序设置 isClicked = true

我的问题是,当我看到按钮上应用的样式时,单击后,我看到 'device_name_button greencolorstyle myClass'。而点击它应该只有 'device_name_button''myClass'.

如何在有人点击此按钮时从该按钮中删除另一个 类?

首先,几个可能的解决方案。

  1. 您更新数组中组件的状态。您的 ngClass 绑定将完成剩下的工作。这是我的建议,因为这意味着您的视图仅取决于数据,但我知道改变数组中的元素并不总是那么容易。

  2. 您设置了不同的 ngClass 条件,以便根据组件的状态和被点击来应用颜色 类。

其次,您不应该在属性中使用字符串插值。您应该使用属性绑定:[id]="'Button' + index".

我用两步法解决了这个问题。首先,我创建了一个名为“custom-button”的自定义组件。我用自定义元素替换了 Html 中的按钮元素。通过这种方式,我对数组的每个项目都有了句柄。然后我创建了另外三种样式,即“graywhitecolorstyle”、“greenwhitecolorstyle”和“redwhitecolorstyle”,在已经提到的三种之上。

接下来是自定义按钮组件的html。

<div class="device_name_button"  matTooltipPosition="right"
[ngClass]="{'whiteredbackground':hardwareComponent.isClicked && 
hardwareComponent.status=='Faulted' 
,'greencolorstyle':hardwareComponent.status=='Available' && 
hardwareComponent.isClicked==false,'greenwhitecolorstyle':
hardwareComponent.status=='Available' && hardwareComponent.isClicked, 
'redcolorstyle': hardwareComponent.status=='Faulted' && 
!hardwareComponent.isClicked,
'graycolorstyle':hardwareComponent.status=='Unavailable' && 
!hardwareComponent.isClicked,'graywhitecolorstyle':
hardwareComponent.status=='Unavailable' && hardwareComponent.isClicked}"
(click)="selectHardware()" ><p>{{title}}</p>
</div>