Assign Style with *Ngif Evaluation in Angular2

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.

2 Answers

*ngIf would work if you change {{myVar}} to myVar(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>
6

To complete Panjak Parkar's answer, and to answer to the question in the title (style)

<li *ngFor="let item of myList">
    <div [ngStyle]="{'background-color':item.country === 'UK' ? 'green' : 'red'}">
    </div>
</li>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.