angular2 组件内的 iframe,属性“contentWindow”在类型“HTMLElement”上不存在

新手上路,请多包涵

我在 angular2 组件中有一个 iframe,我试图通过访问 contentWindow 来更改 iframe 的内容。

iframe 应该包含一个简单的按钮。

我的代码:

     import { Component } from '@angular/core';
    @Component({
      moduleId: module.id,
      selector: 'component-iframe',
      template: '<iframe id="iframe"></iframe>'
    })
    export class ComponentIframe  {
      constructor() {
        let iframe = document.getElementById('iframe');
        let content = '<button id="button" class="button" >My button </button>';
        let doc =  iframe.contentDocument || iframe.contentWindow;
        doc.open();
        doc.write(content);
      doc.close();
    }
   }

如果我注释构造函数的代码并启动应用程序,它会正确编译和运行。然后我取消注释并且所有运行完美(按钮出现在 iframe 中)。

如果我反注释代码然后启动应用程序 (npm start) 我有编译错误消息:

类型“HTMLElement”上不存在属性“contentWindow”

.

我还尝试了将构造函数的代码放入 ngOnInit()、ngAfterContentInit()、ngAfterViewInit() 的替代方法,但错误仍然存在。

原文由 gabriela 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

执行构造函数时,DOM 中尚不存在模板

改用

import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
  moduleId: module.id,
  selector: 'component-iframe',
  template: '<iframe #iframe></iframe>'
})
export class ComponentIframe  {
  @ViewChild('iframe') iframe: ElementRef;

  ngAfterViewInit() {
    let content = '<button id="button" class="button" >My button </button>';
    let doc =  this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow;
    doc.open();
    doc.write(content);
    doc.close();
  }
}

原文由 Günter Zöchbauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

用这个:

 let iframe = document.getElementById('iframe') as HTMLIFrameElement

原文由 Eldos Narbay 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题