简体   繁体   English

如何应用条件式CSS?

[英]How to apply conditional css?

I have a component item that represents a card with the data about the item. 我有一个组件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: 由于所有卡都具有相同的结构(每张卡上都显示了价格/颜色/尺寸/照片类别,仅此而已,因此,我想应用条件CSS,但我不知道如何操作,因为这些卡的风格基于以下内容(略有不同):

  • 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). 它们是该组件还是该组件的一部分(URL可以相同)。 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. 例如,在单个视图中,第一个组件具有X卡样式,而第二个组件具有Y卡样式-但这些卡具有相同的数据。

I'd really appriciate any suggestion! 我真的很喜欢任何建议!

You can use NgClass to add conditional classes. 您可以使用NgClass添加条件类。 For more info, refer the documentation - https://angular.io/api/common/NgClass 有关更多信息,请参阅文档-https://angular.io/api/common/NgClass

<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: 我们可以像这样轻松切换CSS类:

<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: NgClass还可以一次分配多个静态类名称:

We can also use ngClass to assign multiple CSS classes based on multiple conditions. 我们还可以使用ngClass根据多个条件分配多个CSS类。

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


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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM