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