Attribute property binding for background-image url in Angular 2

前端 未结 4 465
臣服心动
臣服心动 2020-12-05 06:38

I have been struggling to figure out the best way to dynamically change the background-image attribute in a number of Angular 2 components.

相关标签:
4条回答
  • 2020-12-05 07:06

    You don't need to use NgStyle. You can also do this:

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

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

    0 讨论(0)
  • 2020-12-05 07:16

    The main reason is simple, you declared a global variable as blankImage but in the template you called image instead of blankImage.

    Your ts code variable blankImage

    blankImage: string = '../assets/.../camera.png';
    

    Your template code variable image

    <div class="profile-image" [ngStyle]="{'background-image': 'url(' + image + ')'}"></div>
    
    0 讨论(0)
  • 2020-12-05 07:19

    I think that you should use something like that:

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

    where image is a property of your component.

    See this question:

    • How to add background-image using ngStyle (angular2)?
    0 讨论(0)
  • 2020-12-05 07:26

    that's wrong

    I think you should add:

    <div class="profile-image" [ngStyle]="{ 'backgroundImage': url({{image}})">
    

    Regards

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