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

查看:11
本文介绍了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天全站免登陆