According to Angular documentation, you need to sanitize urls before you use them, one way mentioned is bypassSecurityTrustStyle
, but they don't tell you how to use it. This is how:
// inject DomSantisizer
private sanitizer: DomSanitizer
Sanitize the style value, including "url":
this.bgstyle = this.sanitizer.bypassSecurityTrustStyle(`url("${imageUrl}")`);
And in HTML template:
<div [style.background-image]="bgstyle" ></div>
Resource: Angular Docs
Update
Now I would usually by pass security when I know the source (not user generated content from storage), because I tend to be too lazy. Angular docs have since been updated, and it is now looking better. Here is what I tried with different SecurityContext
to properly sanitize:
this.bgstyle = this.sanitizer.sanitize(SecurityContext.STYLE, `url("${this.source.url}")`);
This one works for background images set by style. For setting an image source, HTML
, NONE
, URL
, and STYLE
all worked. For RESOURCE_URL
and SCRIPT
, it shall fail to sanitize. Normally.
Shout out to @bagratzakaryan for reviving this old article and correcting me.
Top comments (4)
I think you are getting it wrong, because this method used to bypass the sanity check, in other words skip it, check the text from Angular.io
"Calling any of the bypassSecurityTrust... APIs disables Angular's built-in sanitization for the value passed in. Carefully check and audit all values and code paths going into this call. Make sure any user data is appropriately escaped for this security context. For more detail, see the Security Guide"
understood, it is bypassing, bad use of language I guess :) but the notion is, if you know the source you should go for it, otherwise, hmm, how do u go on displaying the background image if Angular prohibits it?
you can use simple sanitize, even you can find about it in pure javascript
angular.io/api/platform-browser/Do...
developer.mozilla.org/en-US/docs/W...
i've done this a long time ago i don't remember why i skipped that, i will try again and update, thank you.