Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular mix different [ngClass] expressions

Tags:

css

angular

I would like to mix the [ngClass] Expressions in Angular, first I want to add an array of classes to my component and then I would also like to add a class based on a Boolean expression. I can add an array with <li [ngClass]="item.status"> and I can add a class based on a Boolean expression with <li [ngClass]="{active: item.active}">

Note: item.status is an array like item.status=['done', 'progressed']

But how can I mix both styles? The following doesn't work because only the attribute is duplicate. <li [ngClass]="item.status" [ngClass]="{active: item.active}">

Thanks in advance


2 Answers

Because you could not have [ngClass] multiple time in same element you could use the combination of [ngClass] and class. When use class in this way with interpolation then you could add several classes as well. Try to use following way.

E.g. HTML

<li  class="t-size {{item.status.join(' ')}}" [ngClass]="{'active': item.active }">

E.g. Component

 item = {
    status : ['done', 'progressed'],
    active: true
  }

E.g. CSS

.done{
  font-weight: bold;
}

.progressed{
  color:blue;
}

.t-size{
  font-size: 2rem;
}

.active{
  background-color: yellowgreen;
}

WORKING DEMO

Hope this will help to you! :)

like image 72
coder Avatar answered Mar 31 '26 07:03

coder


You can use both as below:

<li [class]="item.status" [ngClass]="{active: item.active}">

You cannot use ngClass more than one time in the single element.

like image 32
Niral Munjariya Avatar answered Mar 31 '26 07:03

Niral Munjariya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!