【问题标题】:Angular 6 iframe bindingAngular 6 iframe 绑定
【发布时间】:2019-02-22 06:08:29
【问题描述】:
有一个变量存储 iframe 代码。
我想将它绑定在一个 div 中,但没有任何效果。
html:
<div class="top-image" [innerHTML]="yt"></div>
ts:
yt = '<iframe class="w-100" src="https://www.youtube.com/embed/KS76EghdCcY?rel=0&controls=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
解决办法是什么?
【问题讨论】:
标签:
html
angular
typescript
iframe
【解决方案1】:
您可能会收到警告说它是不安全的 HTML。这就是为什么 Angular 不在 div 内渲染它。
你必须DomSanitize它:
<div class="top-image" [innerHTML]="yt | safe: 'html'"></div>
这是管道courtesy Swarna Kishore。
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html':
return this.sanitizer.bypassSecurityTrustHtml(value);
case 'style':
return this.sanitizer.bypassSecurityTrustStyle(value);
case 'script':
return this.sanitizer.bypassSecurityTrustScript(value);
case 'url':
return this.sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl':
return this.sanitizer.bypassSecurityTrustResourceUrl(value);
default:
throw new Error(`Invalid safe type specified: ${type}`);
}
}
}
这是一个Sample StackBlitz。