March 21, 2022

Angular - Add conditional css class

Angular provides multiple ways to add css classes based on conditions.

Lets say we have a div and we want to apply the classes myclass1, myclass2, myclass3 based on different conditions using a variable counter defined in the component class.

Following are the different snytax methods we can use to add css class with conditions.

Method # 1

Add myclass1, if the counter is equal to 1

    <div [class.myclass1]="counter === 1">

Method # 2

Add myclass1, if the counter is equal to 1

	<div [ngClass]="{'myclass1' : counter === 1}">

Add myclass2, if the counter is greater than 1

	<div [ngClass]="{'myclass2' : counter > 1}">

You can use the same syntax to add multiple classes with their own conditions, each class-condition pair will be spearated by a comma.

For example, here the myclass1 will be added if the counter's value is 1, myclass2 will be added if the counter's value is 2, and myclass3 if the counter has a value greater than 2

   <div [ngClass]="{'myclass1': counter === 1, 'myclass2' : counter === 2 }, 
        'myclass3' : counter > 2 }">

Method # 3

We can use the ternary operator to pick one of the two classes.

If the counter's value is 1, then myclass1 will be added, else myclass2 will be applied.

    <div [ngClass]="counter == 1 ? 'myclass1' : 'myclass2'">

Method # 4

You can write a function inside the component which will return the the class(es) to be added based on some complex condition.

    <div [class]="getClass(6)">

The function will return class names like this:

  getClass(count: number){
    var classList='';

    if(count === 1){
       classList = 'myclass1'; 
    }else if (count > 1 && count < 5){
        classList = 'myclass2';
    }else if(count > 5){
        classList = 'myclass2 myclass3';
    }
    return classList;
  }
}

No comments:

Post a Comment