1

I have this component here:

import { Component } from '@angular/core';
@Component({
    selector: 'component-a',
    templateUrl: '../html/componenta.html'
})
export class ComponetA {
 color_class:string = "red_bg";
}

My css for .red_bg is:

.red_bg{background-color:red}

Now, in my componenta.html, when I attach the class to a button using ngClass, it works perfect, here is the snippet <button [ngClass]="{'red_bg': 1===1}">Click</button> My question is how do I use ngClass and get the value of the class name from the component? Here is what I tried but didn't work: <button [ngClass]="{color_class: 1===1}">Click</button> I also tried interpolating this way <button [ngClass]="{'{{color_class}}': 1===1}">Click</button> but still didn't work. Thanks in advance

Akkusativobjekt
  • 2,005
  • 1
  • 21
  • 26
Wafula Samuel
  • 530
  • 1
  • 8
  • 25
  • 1
    Possible duplicate of [Dynamic classname inside ngClass in angular 2](https://stackoverflow.com/questions/37090877/dynamic-classname-inside-ngclass-in-angular-2) – anoop May 30 '17 at 09:03

2 Answers2

2

You can do it in below way:

HTML

<div [ngClass]="getCSSClass('someExpression')">
</div>

TS

getCSSClass(flag:string) {
  let cssClass;

  if(flag == 'one') {  
     cssClass = {
       'one': true
     }  
  } else {  
     cssClass = {
       'two': true 
     }  
  }
  return cssClass;
}   
Suneet Bansal
  • 2,664
  • 1
  • 14
  • 18
1

I know that these works:

<button [ngClass]="color_class">Click</button>

or

<button [className]="color_class">Click</button>

or

<button [class]="color_class">Click</button>
TK Omble
  • 369
  • 3
  • 8