user3340372
user3340372

Reputation:

Angular mix different [ngClass] expressions

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

Upvotes: 3

Views: 1851

Answers (4)

coder
coder

Reputation: 8702

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! :)

Upvotes: 2

Md. Abu Sayed
Md. Abu Sayed

Reputation: 2486

you can try this code here your app component is

member = true;
paidAmount = true;
setMyClass() {
    let classes =  {
         member: this.someProperty,    
         paid: this.paidAmount, 
    };
    return classes;
}

where 'member' and 'paid' is class name


and your template use this similar code

<div class="myclass" [ngClass]="setMyClass()">Call to Action</div>

Upvotes: 0

Phil
Phil

Reputation: 7566

You can do [class.myClass]="booleanExpression", but I don't recommend adding it together with [ngClass] because then you could have a class multiple times.

Instead I would recommend either making [class.myClass]="booleanExpression" for each and every class you use in that HTML-tag (keep in mind the "booleanExpression" can set/unset more than one class so it would not increase the lines of code in your .ts file, only in the template). Or I would make a getter method for [ngClass]:

[ngClass]="liClasses"

get liClasses(): string {
    const result = "";
    if (conditionOne) { result += " myClassOne"}
    if (conditionTwo) { result += " myClassTwo"}
    return result;
}

note that solution 1) is more perfomant as getter-methods get triggered on every change-detection and not only when conditionOne or conditionTwo changes.

Upvotes: 0

Niral Munjariya
Niral Munjariya

Reputation: 1371

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.

Upvotes: 1

Related Questions