Combine [NgStyle] With Condition (if..else)

Solution 1:

One can also use this kind of condition:

<div [ngStyle]="myBooleanVar && {'color': 'red'}"></div>

It requires a bit less string concatenation...

Solution 2:

Using a ternary operator inside the ngStyle binding will function as an if/else condition.

<div [ngStyle]="{'background-image': 'url(' + value ? image : otherImage + ')'}"></div>

Solution 3:

The previous answers did not work for me, so I decided to improve this.

You should work with url(''), and not with value.

<li *ngFor="let item of items">
  <div
    class="img-wrapper"
    [ngStyle]="{'background-image': !item.featured ? 'url(\'images/img1.png\')' : 'url(\'images/img2.png\')'}">
  </div>
</li>

Solution 4:

You can use this as follows:

<div [style.background-image]="value ? 'url(' + imgLink + ')' : 'url(' + defaultLink + ')'"></div>

Solution 5:

To add and simplify Günter Zöchbauer's the example incase using (if...else) to set something else than background image :

<p [ngStyle]="value == 10 && { 'font-weight': 'bold' }">