我有一系列产品:
product_type_one = [
{'description': 'Type one sample one', 'type': 'one', 'image': '../assets/1.jpg'},
{'description': 'Type one sample two', 'type': 'one', 'image': '../assets/2.jpg'},
{'description': 'Type one sample three', 'type': 'one', 'image': '../assets/3.jpg'},
]
我正在迭代这个数组来创建mdl-cards,我希望每张产品卡都有自己的图像背景。
我的模板:
<mdl-card *ngFor="let product of selectedProduct" class="demo-card-event" mdl-shadow="2" style="background-image: url({{product.image}})">
<mdl-card-title mdl-card-expand>
<h4>
{{product.description}}
</h4>
</mdl-card-title>
</mdl-card>
到目前为止,我没有收到任何错误,但是警告说WARNING: sanitizing unsafe style value background-image: url(../assets/1.jpg)
我创建了一个如下管道:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitizer:DomSanitizer){}
transform(html) {
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
我可以在哪里将其插入模板以便渲染图像?
答案 0 :(得分:3)
尝试在 url
bypassSecurityTrustStyle
语句
<mdl-card *ngFor="let product of selectedProduct" class="demo-card-event" mdl-shadow="2" [style.background-image]="product.image | safeHtml">
<mdl-card-title mdl-card-expand>
<h4>
{{product.description}}
</h4>
</mdl-card-title>
</mdl-card>
然后,
import { Pipe } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name: 'safeHtml'})
export class SafeHtml {
constructor(private sanitizer:DomSanitizer){}
transform(html) {
return this.sanitization.bypassSecurityTrustStyle('url(' + html+ ')');
}
}