Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background color of the button on click

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

like image 320
surazzarus Avatar asked Aug 06 '18 21:08

surazzarus


People also ask

How do I change the background color of a button in HTML?

All style elements in your HTML button tag should be placed within quotation marks. Type background-color: in the quotation marks after "style=". This element is used to change the background color of the button. Type a color name or hexadecimal code after "background-color:".

How can change background image of button click in HTML?

The default button in HTML can be changed to an image using CSS. The required button is selected using the respective CSS selector. The background property can then be set to include a background image and change the image type as required. The border of the button can also be removed to show only the image itself.

How can change background color of button click in jquery?

JavaScript Code:$("div"). on( "click", "button", function( event ) { $(event. delegateTarget ). css( "background-color", "green"); });


2 Answers

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

like image 163
kboul Avatar answered Nov 06 '22 09:11

kboul


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.

like image 36
ConnorsFan Avatar answered Nov 06 '22 07:11

ConnorsFan