Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Class Binding

Tags:

angular

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.

like image 601
nXn Avatar asked Aug 10 '26 20:08

nXn


2 Answers


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>
like image 140
Surjeet Bhadauriya Avatar answered Aug 13 '26 13:08

Surjeet Bhadauriya


Try like this:

<h2 [ngClass]="textrun ? 'text-error':'text-success'">hai</h2>

or,

<h2 [ngClass]="{'text-error': textrun, 'text-success': !textrun }">hai</h2>

Demo

like image 24
Adrita Sharma Avatar answered Aug 13 '26 12:08

Adrita Sharma