angular2 组件内的 iframe,“HTMLElement"类型上不存在属性“contentWindow" [英] iframe inside angular2 component, Property 'contentWindow' does not exist on type 'HTMLElement'

查看:48
本文介绍了angular2 组件内的 iframe,“HTMLElement"类型上不存在属性“contentWindow"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an iframe inside a angular2 component, and I am trying to change the content of the iframe by accessing the contentWindow.
The iframe should contain a simple button.

我的代码:

    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 中).

If I comment the constructor's code and start the app, it compiles and runs correctly. Then I uncomment and all runs perfectly (the button is present in the iframe).

如果我对代码进行注释,然后启动应用程序(npm start),我会遇到编译错误并显示以下消息:

If I decomment the code then start the app (npm start) I have compilation bugs with the message:

HTMLElement"类型上不存在属性contentWindow"

Property 'contentWindow' does not exist on type 'HTMLElement'

.

我也尝试了将 costructor 的代码放入 ngOnInit()、ngAfterContentInit()、ngAfterViewInit() 的替代方法,但错误仍然存​​在.

I also tried the alternative of putting the costructor's code into ngOnInit(), ngAfterContentInit(), ngAfterViewInit() but the error persists.

推荐答案

构造函数执行时模板还不存在

The template doesn't exist in the DOM yet when the constructor is executed

改用

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();
  }
}

这篇关于angular2 组件内的 iframe,“HTMLElement"类型上不存在属性“contentWindow"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆