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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 12:11:47  来源:igfitidea点击:

assign style with *ngIf evaluation in angular2

cssangular

提问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 myVarand 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 myVarand 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 ngClasshere, 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>