Why does sanitizer.bypassSecurityTrustStyle return a warning when setting the [style.background-image] attribute?
I have a simple piece of code that won't work:
<div class="cover"
[style.background-image]="sanitizer.bypassSecurityTrustStyle('url(/assets/img/picture (1).jpg)')">
</div>
sanitizer.bypassSecurityTrustStyle
returns the following message:
SafeValue must use [property]=binding: url(/assets/img/picture (1).jpg) (see http://g.co/ng/security#xss)
Also tried to move sanitization to custom channel, the result is the same.
Angular completely ignores when trying the following solutions style.background-image
:
-
[style.background-image]="'url(' + photo + ')'"
-
[ngStyle]="{'background-image': 'url(' + photo + ')'}"
Why?
Angular: 5.2.4
The problem occurs when you have an image url with spaces in it and the string that is passed to the css url () does not contain quotes:
[style.background-image]="'url(' + photo + ')'"
The above code works great when your url has no spaces. If there are spaces, just wrap the actual image url with single quotes:
[style.background-image]="'url(\'' + photo + '\')'"
By the way, if that still doesn't work, try disabling Angular's built-in sanitization for the value passed to:
bypassSecurityTrustStyle(style)
You can create a channel for this:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
constructor(
private sanitizer: DomSanitizer
) { }
transform(style) {
return this.sanitizer.bypassSecurityTrustStyle(style);
}
}