typescript Angular 6 iframe 绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52382608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 6 iframe binding
提问by Bálint Bakos
There is a variable that stores iframe code. I want to bind this in a div, but nothing work.
有一个存储 iframe 代码的变量。我想将它绑定在一个 div 中,但没有任何效果。
html:
html:
<div class="top-image" [innerHTML]="yt"></div>
ts:
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>';
What is the solution?
解决办法是什么?
回答by SiddAjmera
You probably might get a warning saying that it's unsafe HTML. That's why Angular is not rendering it inside the div
.
您可能会收到一条警告,指出它是不安全的 HTML。这就是为什么 Angular 没有在div
.
You'll have to DomSanitize
it:
你必须这样DomSanitize
做:
<div class="top-image" [innerHTML]="yt | safe: 'html'"></div>
Here's the pipe courtesy Swarna Kishore.
这是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}`);
}
}
}
Here's a Sample StackBlitz.
这是一个示例 StackBlitz。