【问题标题】:How to remove style on click of a button如何在单击按钮时删除样式
【发布时间】:2022-01-05 14:30:52
【问题描述】:

我有一个在 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'

当有人单击此按钮时,如何从该按钮中删除其他类?

【问题讨论】:

  • 能否添加点击时执行的代码

标签: angular ng-class angular13


【解决方案1】:

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

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

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

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

【讨论】:

  • 我已经修改了模型类并添加了 isClicked 属性。我添加了两个 ngClass 元素。这一次,按钮始终是白色背景。
  • 我在单击事件处理程序中将 IsClicked 更改为 true,this.hardwareDetails=_hardwareComponent.components; _hardwareComponent.isClicked=true;让 index = this.componentList.indexOf(_hardwareComponent); this.componentList[index].isClicked=true; }
【解决方案2】:

我使用两步过程解决了它。首先,我创建了一个名为“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>

【讨论】:

  • 这是一个不必要的复杂答案,它不遵循 Angular 最佳实践,以防万一其他用户碰巧发现它。
猜你喜欢
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多