angular
2017-04-12 47 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代碼中,而不是在模板中有太多的代碼。

相關問題