ウェブサイト検索

angular - クリック時にボタンの背景色を変更する


クリックするとテキストがenableとdisableに変わるボタンがあります。

ボタンの色もどうやって変更できますか、

例えば、enable のときは緑に、disable のときは赤に変更する

<button (click)="enableDisableRule()">{{status}}</button>

コンポーネント

toggle = true;
status = 'Enable'; 

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

どんな助けでも感謝します。ありがとうございます

回答 #1

その目的のために、toggle のブール値に基づいてトリガーされる2つの異なる CSS クラスを使用して ngClass ディレクティブを使用できます:

テンプレート:

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

デモ

回答 #2

背景色だけを変更したい場合は、スタイルバインディングを使用できます:

<button [style.background-color]="toggle ? 'green' : 'red'" (click)="enableDisableRule()">
  {{status}}
</button>

デモについてはこのStackBlitzを参照してください。

関連記事