我知道有类似的问题,所以.. domSanitizer和WARNING: 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})'`);
}
但我认为这是因为它无法找到背景图像oninit ..因为它是从外部api拉入的
任何帮助,将不胜感激!谢谢
编辑
我也试过这个......
ngOnChanges(changes: SimpleChanges) {
this.backgroundImage = this.sanitization.bypassSecurityTrustStyle(`'url(${this.item.fields.asset[0].fields.backgroundImage.fields.file.url})'`);
}
但这似乎也没有奏效
事件虽然你的项目在模板中有?
,但你仍然在课堂上有this.item
。这意味着,您需要确保this.item始终存在。这就是你得到这个错误的原因。
我想出了一个工作,而不是使用一个消毒的网址,我只是这样使用[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>