Angular 6 iframe绑定

Bál*_*kos 3 html iframe typescript angular

有一个存储iframe代码的变量.我想在div中绑定它,但没有任何效果.

HTML:

<div class="top-image" [innerHTML]="yt"></div>
Run Code Online (Sandbox Code Playgroud)

TS:

yt = '<iframe class="w-100" src="https://www.youtube.com/embed/KS76EghdCcY?rel=0&amp;controls=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
Run Code Online (Sandbox Code Playgroud)

解决办法是什么?

Sid*_*era 13

您可能会收到警告,说它是不安全的HTML.这就是为什么Angular没有将它渲染到内部的原因div.

你必须DomSanitize这样:

<div class="top-image" [innerHTML]="yt | safe: 'html'"></div>
Run Code Online (Sandbox Code Playgroud)

这是管道礼貌的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}`);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这是一个Sample StackBlitz.