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

2019-02-04 06:27发布

I have read NgStyle Documentation For Angular2. Little bit confusing for me. Any idea on how to use NgStyle with condition like (if...else) to set background image of any element?

4条回答
贪生不怕死
2楼-- · 2019-02-04 06:50

You can use this as follows:

<div [style.background-image] = "value ? 'url('+imgLink+')' : 'url('+defaultLink+')'"></div>
查看更多
Summer. ? 凉城
3楼-- · 2019-02-04 07:06

The above 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>
查看更多
We Are One
4楼-- · 2019-02-04 07:07

One can also use this kind of condition:

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

It requires a bit less string concatenation...

查看更多
Ridiculous、
5楼-- · 2019-02-04 07:09

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

<div [ngStyle]="{'background-image': 'url(' + value ? image : otherImage + ')'}"></div>
查看更多
登录 后发表回答