Angular 7 与 iframe 链接

mul*_*123 4 iframe angular

我试图在 iframe 内绑定一个链接 (project.projectUrl),但似乎无法让它工作。我正在尝试将我的 JSON 文件中的 projectUrl 绑定到 iframe src,以便我可以在可能的情况下从模式中动态显示 iframe。请在下面的评论中查看我的代码。

小智 14

您需要清理src。https://angular.io/api/platform-b​​rowser/DomSanitizer#bypassSecurityTrustResourceUrl

在组件构造函数中执行此操作的方法之一:

constructor(sanitizer: DomSanitizer, ....)
Run Code Online (Sandbox Code Playgroud)

进而

<iframe [src]="sanitizer.bypassSecurityTrustResourceUrl(project.projectUrl)" height="600" width="1000"></iframe>

Run Code Online (Sandbox Code Playgroud)

  • 但这并不能起到消毒作用,不是吗?它实际上是在说“不要消毒,但无论如何都要相信” (3认同)

Ash*_*yan 5

我用javascript解决了我的问题。

在这种情况下,您不应该使用[]{{}}

通过 viewChild 或其他方式将元素放入模板并将属性设置到其中。

这是代码示例。

HTML 模板

<iframe #iframe height="600" width="1000"></iframe>
Run Code Online (Sandbox Code Playgroud)

在您的组件中

export class Component implements AfterViewInit {

   @ViewChild('iframe') iframe: ElementRef

  ngAfterViewInit() {
   this.iframe.nativeElement.setAttribute('src', project.projectUrl);
  }
}

Run Code Online (Sandbox Code Playgroud)