将多个字符串值检查为OR表达式以与NgClass一起使用

时间:2017-04-12 12:20:58

标签: angular

我正在尝试使用一个表达式来检查表达式中的任何给定值。我设法做到了这一点:

<h2 class="heading" [ngClass]='{"redBackground" : info?.title == "Relationships" || info?.title == "In The Anime" ||  info?.title == "Anime" || info?.title == "Appearance" ||  info?.title == "Relationships" || info?.title == "In The Anime"}'>{{ info.title }}</h2>

寻找更清洁的方法

1 个答案:

答案 0 :(得分:0)

这显着缩短了:

<h2 class="heading" [ngClass]='{"redBackground" : ["Relationships", "In The Anime", "Anime", "Appearance", "Relationships", "In The Anime"].indexOf(info?.title) >= 0}'>{{ info.title }}</h2>

Installment Payments(IE不支持)

<h2 class="heading" [ngClass]='{"redBackground" : ["Relationships", "In The Anime", "Anime", "Appearance", "Relationships", "In The Anime"].includes(info?.title)}'>{{ info.title }}</h2>

我建议将其移至TS代码,而不是在模板中包含太多代码。