[英]Angular2 use *ngif to set class name in html code
我已經嘗試了一些方法,因為我正在構建天氣儀表板。
我使用http加載天氣數據並進行訂閱,因此我得到了一個可以觀察到的信息,我無法像打字稿中的數組那樣添加新屬性。
例如,我想查看每個天氣數據,並查看值是否大於70°F,並告訴weatherdata項目添加新屬性“ weatherdata-sun-hot”。 否則,它應該使用其他類名“ weatherdata-sun-normal”,我將使用它作為類名,稍后通過插值將其放入html中。
所以我的想法是用html模板解決這個問題
到目前為止,我的代碼確實在這里
<ul>
<li *ngFor="let item of weatherdata">{{item.dt_txt}} | {{item.main.temp_min}} -> {{item.main.temp_max}}</li>
</ul>
有解決這個問題的優雅方法嗎?
謝謝你的幫助。
您需要使用ngClass指令:
<ul>
<li *ngFor="let item of weatherdata" [ngClass]="{'weatherdata-sun-hot': item.main.temp_min > 70, 'weatherdata-sun-normal': item.main.temp_min <= 70}">
{{item.dt_txt}} | {{item.main.temp_min}} -> {{item.main.temp_max}}
</li>
</ul>
或者,您可以在組件的代碼中完成它並綁定到它:
模板
<ul>
<li *ngFor="let item of weatherdata" [ngClass]="tempClass(item)">
{{item.dt_txt}} | {{item.main.temp_min}} -> {{item.main.temp_max}}
</li>
</ul>
零件
@Component(...)
class MyComponent {
tempClass(item): any {
const hot = item.main.temp_min > 70;
return {
'weatherdata-sun-hot': hot,
'weatherdata-sun-normal': !hot
};
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.