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



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

<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>

寻找更清洁的方法

这明显更短:

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

或 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes(在 IE 中不受支持(

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

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

最新更新