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

喜你入骨 提交于 2019-12-17 18:12:56

问题


I have read NgStyle Documentation For Angular 2, and it is a little bit confusing for me. How do I use NgStyle with condition like (if...else) to set background image of any element?


回答1:


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

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



回答2:


One can also use this kind of condition:

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

It requires a bit less string concatenation...




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



回答4:


You can use this as follows:

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



回答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' }">



回答6:


Use:

[ngStyle]="{'background-image': 'url(' +1=1 ? ../../assets/img/emp-user.png : ../../assets/img/emp-default.jpg + ')'}"


来源:https://stackoverflow.com/questions/37051496/combine-ngstyle-with-condition-if-else

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!