domSanitizer SafeStyle不工作Angular 5

时间:2018-03-06 00:36:24

标签: javascript angular typescript

我知道有类似的问题。domSanitizerWARNING: sanitizing unsafe style value url我已经完成了那些已经说过的话,我似乎无法让它发挥作用......

app.component.html

<div *ngIf="item?.fields?.asset[0]?.fields?.backgroundImage" class="program-item_background" [style.background]=backgroundImage></div>

app.component.ts

import { DomSanitizer, SafeResourceUrl, SafeUrl, SafeStyle } from '@angular/platform-browser';

export class ProgramItemComponent implements OnInit, OnChanges, Sanitizer {
    @Input() item: Entry<any>; // Program Item getting passed down from the parent        
    backgroundImage: SafeStyle;

constructor(
    private sanitization: DomSanitizer
) { }

ngOnChanges(changes: SimpleChanges) {
    this.backgroundImage = this.safeStyle(this.item.fields.asset[0].fields.backgroundImage.fields.file.url);
}

safeStyle(url){
    return this.sanitization.bypassSecurityTrustStyle(`'url(${url})'`);
}

我也在控制台中收到此错误.. enter image description here

但我认为那是因为它无法找到backgroundImage oninit ..因为它是从外部api中引入的

任何帮助将不胜感激! 感谢

修改

我也试过这个......

ngOnChanges(changes: SimpleChanges) {
    this.backgroundImage = this.sanitization.bypassSecurityTrustStyle(`'url(${this.item.fields.asset[0].fields.backgroundImage.fields.file.url})'`);
}

但这似乎无法正常工作

2 个答案:

答案 0 :(得分:0)

虽然您的项目在模板中有?,但您在课程中仍然有this.item。这意味着,您需要确保this.item始终存在。这就是你得到这个错误的原因。

答案 1 :(得分:0)

我想出了一个解决方法,而不是使用我刚刚使用[ngStyle]的已清理网址

<div *ngIf="item?.fields?.asset[0]?.fields?.backgroundImage" class="program-item_background" [ngStyle]="{'background': 'url(' + this.item.fields.asset[0].fields.backgroundImage.fields.file.url + ') 50% no-repeat'}"></div>