typescript 单击时更改按钮的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51716059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:33:56  来源:igfitidea点击:

Change background color of the button on click

angulartypescriptng-class

提问by surazzarus

I have a button that changed its text to enableand disableon click.

我有一个按钮,改变了它的文本enabledisable上点击。

How can I also change the button color,

我怎样才能改变按钮颜色,

For e.g. change to Green on enableand Red on disable

例如,更改为绿色亮起enable和红色亮起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

任何帮助表示赞赏。谢谢

采纳答案by kboul

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

为此,您可以使用 ngClass 指令使用两个不同的 css 类,这些类将根据 toggle 的布尔值触发:

template:

模板:

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

css

css

.green {
    background-color: green;
}

.red {
    background-color: red;
}

ts

ts

toggle = true;
status = 'Enable'; 

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

Demo

演示

回答by ConnorsFan

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 stackblitzfor a demo.

有关演示,请参阅此 stackblitz

回答by Rach Chen

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

如果您的默认toggle值为 true,则该默认类为.toggle. 使用 Css 优先级替换[ngClass].

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

For the Css order, togglewould be above disable.

对于 Css 订单,toggle将在disable.

.toggle { background-color:green; }
.btn--disable { background-color:red; }

回答by Faisal

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

在按钮上使用 [ngClass] 来应用适当的样式类。

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