CSS 在 angular2 中使用 *ngIf 评估分配样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40002473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
assign style with *ngIf evaluation in angular2
提问by splunk
This is what I have:
这就是我所拥有的:
home.html
主页.html
<li *ngFor="let item of myList">
<div *ngIf="item.messageText === {{myVar}}" class="bordered">{{item.messageText}}</div>
<div *ngIf="item.messageText !== {{myVar}}" class="greyedOut">{{item.messageText}}</div>
</li>
in home.tsI have defined the variable myVar
and I've assigned to it a value.
在home.ts 中,我定义了变量myVar
并为其分配了一个值。
I want to assign bordered class to the element of myList which has a value equal to myVar
and assign another class if that element's value is different.
我想将带边框的类分配给 myList 的元素,该元素的值等于myVar
并分配另一个类,如果该元素的值不同。
回答by Pankaj Parkar
*ngIf would work if you change {{myVar}}
to myVar
(without interpolation) in expression.
如果您在表达式中更改{{myVar}}
为myVar
(无插值),*ngIf 将起作用。
<li *ngFor="let item of myList">
<div *ngIf="item.messageText === myVar" class="bordered">{{item.messageText}}</div>
<div *ngIf="item.messageText !== myVar" class="greyedOut">{{item.messageText}}</div>
</li>
Though I would prefer you to use ngClass
here, more cleaner and better solution.
虽然我更喜欢你在ngClass
这里使用,更清洁和更好的解决方案。
<li *ngFor="let item of myList">
<div [ngClass]="item.messageText == item.messageText ? 'bordered': 'greyedOut'">
{{item.messageText}}
</div>
</li>
OR
或者
<li *ngFor="let item of myList">
<div [ngClass]="{'bordered': item.messageText == item.messageText, 'greyedOut': item.messageText !== item.messageText }">
{{item.messageText}}
</div>
</li>