DEV Community

Ayyash
Ayyash

Posted on • Updated on • Originally published at garage.sekrab.com

Sanitizing background image url in Angular

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
Enter fullscreen mode Exit fullscreen mode

Sanitize the style value, including "url":

this.bgstyle = this.sanitizer.bypassSecurityTrustStyle(`url("${imageUrl}")`);
Enter fullscreen mode Exit fullscreen mode

And in HTML template:

<div [style.background-image]="bgStyle" ></div>
Enter fullscreen mode Exit fullscreen mode

Resource: Angular Docs

Discussion (0)