angular
2017-04-12 24 views 0 likes 
0

我想要使用一个表达式,它将检查表达式中的任何给定值。我已成功地做到这一点有:检查多个字符串值作为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> 

寻找一个更简洁的方法

+0

您可以将逻辑放入一个属性或方法,并且如果匹配任何目标字符串,则返回true。另一种方法是将所有字符串放入数组中,并使用'[“Relationships”,etc] .indexOf(title)!== -1“,但我不记得该位置是否支持该语法。 –

回答

0

这是明显短:

<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代码中,而不是在模板中有太多的代码。

相关问题