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
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:".
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.
JavaScript Code:$("div"). on( "click", "button", function( event ) { $(event. delegateTarget ). css( "background-color", "green"); });
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With