Change background color of the button on click

surazzarus picture surazzarus · Aug 6, 2018 · Viewed 23.3k times · Source

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

Answer

kboul picture kboul · Aug 6, 2018

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