What is the recommended way to dynamically set background image in Angular 4

后端 未结 3 1336
野性不改
野性不改 2021-01-14 01:40

Currently I\'m setting the image background using inline-style.

相关标签:
3条回答
  • 2021-01-14 01:57

    This code has worked for me.

    [style.backgroundImage]="'url('+MEDIA_URL +'/dir/'+data.image+')'"
    

    MEDIA_URL is the base URL of uploaded location.

    Angular CLI: 6.1.3 Angular: 6.1.2

    0 讨论(0)
  • 2021-01-14 02:07

    You can't do it thourgh CSS files. However, you can make your current code little less verbose :

    <div [style.background]="'url(' + section.backgroundSrc + ') no-repeat'"></div>
    

    If angular throws security errors, you will have to sanitize too. So you will do something like this: in HTML file-

    <div [style.background]="background"></div>
    

    in your TS file

    this.background= 
    this.sanitization.bypassSecurityTrustStyle(`url(${this.section.backgroundSrc}) no-repeat`);
    
    0 讨论(0)
  • 2021-01-14 02:15

    Thanks to Harsha Sampath. I did:

    [style.backgroundImage]="'url('+urlToImage+')'"
    

    works in Angular 8, urlToImage is a string property of component, resolved at runtime.

    The other settings of background are fixed in css:

    background-repeat: no-repeat;
    background-position:center center;
    background-size: 100% 100%;
    
    0 讨论(0)
提交回复
热议问题