splunk splunk - 1 month ago 7
CSS Question

assign style with *ngIf evaluation in angular2

This is what I have:

home.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.ts I have defined the variable
myVar
and I've assigned to it a value.

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.

Answer

*ngIf would work if you change {{myVar}} to mayVar(without interpolation) in expression.

<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.

<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>