问题
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>
The 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 a custom pipe, the result is the same.
When trying the following solutions Angular ignores style.background-image
completely:
[style.background-image]="'url(' + photo + ')'"
[ngStyle]="{'background-image': 'url(' + photo + ')'}"
Why?
Angular: 5.2.4
回答1:
The problem occurs when you have an image url with spaces in it and the string, which is passed to css url() is without quotes:
[style.background-image]="'url(' + photo + ')'"
The code above works fine when your url has no spaces. If there are spaces just wrap actual image url with single quotes:
[style.background-image]="'url(\'' + photo + '\')'"
By the way, if this still does not work, try disabling Angular's built-in sanitization for the value passed in:
bypassSecurityTrustStyle(style)
You can create a pipe for that:
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);
}
}
来源:https://stackoverflow.com/questions/49419662/why-sanitizer-bypasssecuritytruststyle-returns-warning-when-setting-style-backg