How to use ngStyle to add background-image? My code doesn\'t work:
this.photo = \'http://dl27.fotosklad.org.ua/20121020/6d0d7b1596285466e8bb06114a88c903.jpg\
My solution, using if..else statement. It is always a good practice if you want to avoid unnecessary frustrations, to check that your variable exists and is set. Otherwise, provide a backup image in case; You can also specify multiple style properties, like background-position: center
, etc.
<div [ngStyle]="{'background-image': this.photo ? 'url(' + this.photo + ')' : 'https://placehold.it/70x70', 'background-position': 'center' }"></div>
I think you could try this:
<div [ngStyle]="{'background-image': 'url(' + photo + ')'}"></div>
From reading your ngStyle
expression, I guess that you missed some "'"...
Also you can try this:
[style.background-image]="'url(' + photo + ')'"