Home > Software design >  Angular : how to properly set multiple conditions with ngClass
Angular : how to properly set multiple conditions with ngClass

Time:06-11

I am trying to create my own UI library using angular and Tailwind, I am facing an issue using ngClass :

  <button
    [ngClass]="{
      'px-4 py-2 text-sm': size === 'md',
      'px-4 py-2 text-base': size === 'lg',
    }"
  >
    My Button
  </button>

I want my class to be one of these above when the condition on the size is met. The problem is when the size equals 'md' and so the first condition is met : the class in the dom is only text-sm instead of px-4 py-2 text-sm

The ngClass documentations says :

keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed

My understanding is that in my example :

  • The first condition is evaluated as true => the class is correctly being setup
  • Then the second condition is evaluated as false => px-4 py-2 text-base is being removed from the class as so the only one remaining is text-sm.

I think I was able to understand the problem, but since I'm new to angular and I would like to learn how to use properly ngClass, does anyone have a solution to solve this ?

CodePudding user response:

Add the common classes to your regular class attribute, like this:

<button
    [ngClass]="{
      'text-sm': size === 'md',
      'text-base': size === 'lg',
    }"
   
  >
    My Button
  </button>

CodePudding user response:

Here you go, do it like this with multiple conditions:

[ngClass]="property  === value1 ? 'css-class-name1' : property  === value2 ? 'css-class-name2' : property  === value3 ? 'css-class-name3' :   'default-css'"
  • Related