Home > Enterprise >  Use default class in ngclass attribute Angular
Use default class in ngclass attribute Angular

Time:10-14

I have got a span which is required to change its classes based on the value inside of it.

So I am following ngclass way like this

<span class="badge " [ngClass]="{'bg-info':item.LifeCycle==='Pipeline',
'bg-primary':item.LifeCycle==='In Progress','bg-warning':item.LifeCycle==='In Close-Down'}">
{{item.LifeCycle}}</span>

But my issue is when if a different value outside of the 3 expressions, the content seems to be not visible ofcourse due to no classes seems to be assigned.

So how to set a default class in ngClass without any expression

CodePudding user response:

You are trying to achieve a switch-case inside ngClass, whereas ngClass only provide multiple if statement for each "CSS class". This should be handled in the components class not template through a switch.

<span class="badge " [ngClass]="getBadgeClass(item.LifeCycle)">
{{item.LifeCycle}}</span>

In the component you can use a switch statement.

    public getBadgeClass(lifeCycle) {
      switch lifeCycle {
      case 'Pipeline' : // all cases  
        return 'bg-primary';
      default: 
        return 'what ever is the default class';
      }
   }

CodePudding user response:

you can set default class using ternary operator, I hope it worked for you.

[ngClass] = "item.LifeCycle==='Pipeline' ? 'bg-info' : 'item.LifeCycle==='In Progress' ? 'bg-primary' : item.LifeCycle==='In Close-Down' ? 'bg-warning' : 'set-default-class'"
  • Related