santubangalore
santubangalore

Reputation: 792

How to remove style on click of a button

I have a button which is inside an ngFor loop. I am styling it like this.

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

I am setting isClicked = true with click event handler.

My problem is that when I see the style being applied on the button, after a click, I see, 'device_name_button greencolorstyle myClass'. Whereas on click it should only have 'device_name_button' and 'myClass'.

How do I remove the other classes from this button when someone clicks on this button?

Upvotes: 0

Views: 1095

Answers (2)

santubangalore
santubangalore

Reputation: 792

I solved it using two step process. First I created a custom-component named "custom-button". I replaced the button element in the Html with custom element. In this way I had a handle on each item of the array. Then I created three more styles namely "graywhitecolorstyle","greenwhitecolorstyle" & "redwhitecolorstyle", over and above the three already mentioned.

Next the html of custom-button component.

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

Upvotes: -2

Will Alexander
Will Alexander

Reputation: 3571

First, a couple of possible solutions.

  1. You update the status of the component in the array. Your ngClass binding will do the rest. This is what I recommend, as it means your view depends only on the data, but I understand that it is not always easy to mutate an element in an array.

  2. You set your ngClass conditions differently in order to apply your color classes according to both the status of the component AND isClicked.

Secondly, you shouldn't be using string interpolation in your attributes. You should be using attribute binding: [id]="'Button' + index".

Upvotes: 1

Related Questions