iframe inside angular2 component, Property 'contentWindow' does not exist on type 'HTMLElement'

前端 未结 7 2070
一整个雨季
一整个雨季 2020-12-03 07:44

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 butt

7条回答
  •  没有蜡笔的小新
    2020-12-03 08:20

    As Günter Zöchbauer has already answered it correctly. I would like to modify it a bit.

    The DOM is not ready in Constructor yet but you can find it ready in ngOnInit event though by using { static: true } property something like this:

    import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
    @Component({
      moduleId: module.id,
      selector: 'component-iframe',
      template: ''
    })
    export class ComponentIframe implements OnInit {
      @ViewChild('iframe', { static: true }) iframe: ElementRef;
    
      ngOnInit() {
        let content = '';
        let doc =  this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow;
        doc.open();
        doc.write(content);
        doc.close();
      }
    }
    

提交回复
热议问题