I have a code on which I have used class binding. When the button is clicked, the color of the font should change based on the value of textrun. textrun changes between true and false.IF true, it should display text in red color else in green color.
TS File
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
textrun=true;
messageClasses={
"text-success": !this.textrun,
"text-error": this.textrun,
"text-info": !this.textrun
}
changetrue(){
this.textrun=false;
console.log("done");
}
}
HTML File
<h2 [ngClass]="messageClasses">hai</h2>
<button (click)="changetrue()">click</button>
css File
.text-success{
color:green;
}
.text-error{
color:red;
}
.text-info{
font-style: italic;
}
EDIT: I needed the same code to work if I have multiple conditions to be applied.
You can use any of the below approach
Approach 1:
<h2 [ngClass]="{'text-error': textrun', 'text-success': !textrun }">hai</h2>
Approach 2:
<h2 [ngClass]="textrun ? 'text-error':'text-success'">hai</h2>
Approach 3:
<h2 [ngClass]="{true:'text-error',false:'text-success'}[textrun]">hai</h2>
Try like this:
<h2 [ngClass]="textrun ? 'text-error':'text-success'">hai</h2>
or,
<h2 [ngClass]="{'text-error': textrun, 'text-success': !textrun }">hai</h2>
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