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

2024-01-09

我在 angular2 组件中有一个 iframe,我试图通过访问 contentWindow 来更改 iframe 的内容。
iframe 应包含一个简单的按钮。

My code:

    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() 中的替代方法,但错误仍然存​​在。


当构造函数执行时,模板还不存在于 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();
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular2 组件内的 iframe,类型“HTMLElement”上不存在属性“contentWindow” 的相关文章

随机推荐