Angular 6 iframe绑定 [英] Angular 6 iframe binding

查看:104
本文介绍了Angular 6 iframe绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个变量用于存储iframe代码. 我想将其绑定到div中,但是没有任何效果.

There is a variable that stores iframe code. I want to bind this in a div, but nothing work.

html:

<div class="top-image" [innerHTML]="yt"></div>

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>';

解决方案是什么?

推荐答案

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

You probably might get a warning saying that it's unsafe HTML. That's why Angular is not rendering it inside the div.

您必须DomSanitize它:

<div class="top-image" [innerHTML]="yt | safe: 'html'"></div>

这是管道由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}`);
    }
  }
}

这是一个 示例StackBlitz .

Here's a Sample StackBlitz.

这篇关于Angular 6 iframe绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆