Change background color of the button on click
Asked Answered
E

4

10

I have a button that changed its text to enable and disable on click.

How can I also change the button color,

For e.g. change to Green on enable and Red on disable

<button (click)="enableDisableRule()">{{status}}</button>

Component

toggle = true;
status = 'Enable'; 

enableDisableRule(job) {
    this.toggle = !this.toggle;
    this.status = this.toggle ? 'Enable' : 'Disable';
}

Any help is appreciated. Thanks

Elainaelaine answered 6/8, 2018 at 21:45 Comment(2)
Have a look at ngClassUnitive
You can use this related questionSunburst
E
12

You can use ngClass directive for that purpose using two different css classes that will be triggered based on the boolean value of toggle :

template:

<button 
    (click)="enableDisableRule()" 
    [ngClass]="{'green' : toggle, 'red': !toggle}">
    {{status}}
</button>

css

.green {
    background-color: green;
}

.red {
    background-color: red;
}

ts

toggle = true;
status = 'Enable'; 

enableDisableRule(job) {
    this.toggle = !this.toggle;
    this.status = this.toggle ? 'Enable' : 'Disable';
}

Demo

Electrocorticogram answered 6/8, 2018 at 21:57 Comment(3)
Perfect but I have 4 buttons and I need to change color button2 for green and button3 return the color. For Example: green, green, red, green....Click in button green change for red and need the button 3 change the color, Do you understand?Android
That is a different scenario in comparison with the current question. You should ask it in a new thread.Electrocorticogram
@Electrocorticogram how would you do this if you have multiple buttons and want the color to change for the background color of the button you click? Right now with this current code, it changes the bg color of all my buttonsRogue
P
5

If you only want to change the background color, you can use style binding:

<button [style.background-color]="toggle ? 'green' : 'red'" (click)="enableDisableRule()">
  {{status}}
</button>

See this stackblitz for a demo.

Principate answered 6/8, 2018 at 22:11 Comment(1)
I have a similar case, The original color is nothing, click once should be red, one more click should be green. Can we do it?Valtin
U
0

Use [ngClass] on your button to apply the appropriate styles class.

<button (click)="enableDisableRule()"
    [ngClass]="{'enabled': toggle, 'disabled': !toggle}">
        {{status}}
</button>
Unitive answered 6/8, 2018 at 22:0 Comment(0)
B
0

if your default toggle was true, that default class is .toggle. Use the Css priority to replace [ngClass].

<button (click)="enableDisableRule()" class="toggle" [class.btn--disable]="!toggle">{{status}}</button>

For the Css order, toggle would be above disable.

.toggle { background-color:green; }
.btn--disable { background-color:red; }
Baptistery answered 7/8, 2018 at 0:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.