Change background color of the button on click

旧街凉风 提交于 2019-12-23 23:14:00

问题


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


回答1:


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.




回答2:


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




回答3:


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

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



回答4:


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


来源:https://stackoverflow.com/questions/51716059/change-background-color-of-the-button-on-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!