Angular2 iframe无法正常工作

时间:2018-03-21 10:32:21

标签: angular iframe angular5

我正在尝试在Angular2上加载iFrame。但是地址是动态加载的。

实时代码为:https://angular-fgzjog.stackblitz.io

在app.coponent.ts内部

<!-- this works -->
    <p>
     iframe address  : {{iFrameSrc}} 
    </p>

<!--- this does not work -->
    <div class="embed-responsive embed-responsive-16by9">
                    <iframe class="embed-responsive-item" [src]="iFrameSrc"></iframe> 
                  </div>

1 个答案:

答案 0 :(得分:1)

Angular会对您尝试放入iframe src的内容进行清理,以防止出现不安全的内容。因此,您必须清理您的网址,告诉Angular您有意添加此网址并确保其安全!

https://angular.io/api/platform-browser/DomSanitizer

因此,要么将此逻辑添加到组件中并调用:

constructor(
 private domSanitizer: DomSanitizer, 
 // ...
) // ...

this.safeiFrameSrc = this.domSanitizer.bypassSecurityTrustUrl(this.iFrameSrc)


<!-- template binding: -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" [src]="safeiFrameSrc"></iframe> 
</div>

或者你也可以创建一个管道:

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {
  constructor(protected sanitizer: DomSanitizer) {}

  transform(value: string, type: string = 'url'): 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(`Unable to bypass security for invalid type: ${type}`);
    }
  }
}

<!-- usage: -->

<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" [src]="iFrameSrc | safe"></iframe> 
</div>    

这应解决问题!