html - Angular 6 iframe 绑定(bind)

标签 html angular typescript iframe

有一个变量存储iframe代码。 我想将其绑定(bind)到一个 div 中,但没有任何效果。

HTML:

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

:

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 中呈现它的原因。

你必须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 .

关于html - Angular 6 iframe 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52382608/

相关文章:

php - 无法使用 jquery.post 获取值(发布)

html - href 链接不适用于图像

json - 使用 Rxjs 不同运算符将整个对象与嵌套进行比较

angular - RxJS mergeMap 运算符中的错误处理

typescript - 如何在 TypeScript 中使用 graphql fetch

node.js - Angular 7/8 - 如何在应用程序组件中获取 url 参数

typescript - 对象文字只能指定已知的属性。类型 'CreateSliceOptions` 中不存在

javascript - jQuery 忽略响应

html - Bootstrap 定位不起作用

angular - 未捕获( promise ): Response with status: 401 Unauthorized for URL