2

I have a component item that represents a card with the data about the item. Since all the cards have the same structure (price/color/size/photo categories are shown on each card, nothing more and nothing less), I would like to apply a conditional CSS, but I don't know how, since the cards' style differ (slightly) based on:

  • price (for example, the card is bigger if the price is lower)
  • if the user has marked it as favorite
  • whether they are a part of this or that component (the URL can be the same). For example, in a single view there is the first component with a X card's style and the second component with a Y card's style - but the cards have the same data.

I'd really appriciate any suggestion!

Rob
  • 14,746
  • 28
  • 47
  • 65
Mandy
  • 107
  • 1
  • 2
  • 9
  • 1
    This question gets asked a lot, there are plenty of examples already such as: https://stackoverflow.com/questions/57645150/how-do-i-conditionally-apply-css-to-a-mat-row-element-on-hover/57645212#57645212, and https://stackoverflow.com/questions/35269179/angular-conditional-class-with-ngclass – chrismclarke Aug 31 '19 at 16:16

2 Answers2

4
<div [className]="'example-class'"></div>

This allows us to add classes based on a condition:

<div [className]="condition ? 'example-class' : 'other-class'"></div>

Or we could build the class name at runtime:

<div [className]="'class' + someValue"></div>

we can easily toggle CSS classes like so:

<div [class.example-class]="condition"></div>

we can assign a variable class name :

<div [ngClass]="seleted-class"></div>

NgClass can also assign multiple static class names all at once:

We can also use ngClass to assign multiple CSS classes based on multiple conditions.

<div
  [ngClass]="{
  'example-class': condition,
  'other-class': !condition
}"
></div>


<div [ngClass]="['example-class', 'other-class']"></div>

source : https://malcoded.com/posts/angular-ngclass/

KLTR
  • 1,263
  • 2
  • 14
  • 37
3

You can use NgClass to add conditional classes. For more info, refer the documentation - https://angular.io/api/common/NgClass

DevLasting
  • 352
  • 1
  • 9