4

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

<div [ngStyle]="{background: 'url(' + section.backgroundSrc + ') no-repeat'}">

However, I'm looking for a more cleaner approach...maybe something like dynamically setting the path in the external stylesheet through angular. However, I'm not sure how it can be done.

5 Answers 5

3

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`);
1
  • 1
    Its giving warning in the browser console WARNING: sanitizing unsafe style value url(./assets/img/section-1-image.png) no-repeat (see http://g.co/ng/security#xss). Commented Sep 8, 2017 at 13:56
1

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%;
1
  • I started to use use the same from Angual 7, and it still work in Angular 8. Commented Sep 2, 2019 at 12:14
0

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

This is the best and easy wasy to handle

[ngStyle]="{'background': 'url(' +(user.photo ? user.photo : '')+') no-repeat 0 0 / cover'}"
0

Html - <div [style.background]="background">

TS - this.section = 'assets/images/bg/waterfallsvg.svg'; this.background = (url(${this.section}) no-repeat);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.