How to add background-image using ngStyle (angular2)?

前端 未结 9 2145
青春惊慌失措
青春惊慌失措 2020-11-28 05:36

How to use ngStyle to add background-image? My code doesn\'t work:

this.photo = \'http://dl27.fotosklad.org.ua/20121020/6d0d7b1596285466e8bb06114a88c903.jpg\         


        
相关标签:
9条回答
  • 2020-11-28 06:01

    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>

    0 讨论(0)
  • 2020-11-28 06:02

    I think you could try this:

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

    From reading your ngStyle expression, I guess that you missed some "'"...

    0 讨论(0)
  • 2020-11-28 06:02

    Also you can try this:

    [style.background-image]="'url(' + photo + ')'"

    0 讨论(0)
提交回复
热议问题