我想在Angular 2应用程序的组件模板中设置DIV的背景图像。但是,我在控制台中始终收到以下警告,但没有得到预期的效果...我不确定动态CSS背景图像是否由于Angular2中的安全限制而被阻止,或者我的HTML模板是否损坏。
这是我在控制台中看到的警告(我将img网址更改为/img/path/is/correct.png
:
警告:清理不安全的样式值url(SafeValue必须使用[property] = binding:/img/path/is/correct.png(请参阅http://g.co/ng/security#xss))(请参阅http:// g.co/ng/security#xss)。
问题是我确实使用DomSanitizationService
Angular2 清理了注入模板的内容。这是模板中的HTML:
<div>
<div>
<div class="header"
*ngIf="image"
[style.background-image]="'url(' + image + ')'">
</div>
<div class="zone">
<div>
<div>
<h1 [innerHTML]="header"></h1>
</div>
<div class="zone__content">
<p
*ngFor="let contentSegment of content"
[innerHTML]="contentSegment"></p>
</div>
</div>
</div>
</div>
</div>
这是组件...
Import {
DomSanitizationService,
SafeHtml,
SafeUrl,
SafeStyle
} from '@angular/platform-browser';
@Component({
selector: 'example',
templateUrl: 'src/content/example.component.html'
})
export class CardComponent implements OnChanges {
public header:SafeHtml;
public content:SafeHtml[];
public image:SafeStyle;
public isActive:boolean;
public isExtended:boolean;
constructor(private sanitization:DomSanitizationService) {
}
ngOnChanges():void {
map(this.element, this);
function map(element:Card, instance:CardComponent):void {
if (element) {
instance.header = instance.sanitization.bypassSecurityTrustHtml(element.header);
instance.content = _.map(instance.element.content, (input:string):SafeHtml => {
return instance.sanitization.bypassSecurityTrustHtml(input);
});
if (element.image) {
/* Here is the problem... I have also used bypassSecurityTrustUrl */
instance.image = instance.sanitization.bypassSecurityTrustStyle(element.image);
} else {
instance.image = null;
}
}
}
}
}
请注意,当我仅使用[src] =“ image”绑定到模板时,例如:
<div *ngIf="image">
<img [src]="image">
</div>
并image
通过了bypassSecurityTrustUrl
一切似乎都工作正常的结果……任何人都可以看到我在做什么错吗?