Angular 2 iframe混淆

Jar*_*her 6 html javascript iframe angular

我试图在Angular 2中更改iframe内部元素的值.我尝试了很多东西,但我一直无法使用引用项目getElementById().我有一个测试场景,它适用于一个案例,而不是另一个案例,这使我更加困惑:

component.html

<iframe #iframe src="assets/test.html"></iframe>
Run Code Online (Sandbox Code Playgroud)

的test.html

<h1 id="wow">Wow</h1>
Run Code Online (Sandbox Code Playgroud)

工作打字稿(打印<h1 id="wow">Wow<h1>)

export class MyComponent implements AfterViewInit {

    @ViewChild('iframe') iframe: ElementRef;

    ngAfterViewInit() {
        var doc = this.iframe.nativeElement.contentDocument;
        doc.open();
        doc.write('<h1 id="wow">Wow</h1>');
        doc.close();
        console.log(doc.getElementById("wow"));
    }
}
Run Code Online (Sandbox Code Playgroud)

非工作打字稿(打印null)

export class MyComponent implements AfterViewInit {

    @ViewChild('iframe') iframe: ElementRef;

    ngAfterViewInit() {
        var doc = this.iframe.nativeElement.contentDocument;
        console.log(doc.getElementById("wow"));
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能让第二个正确打印元素?无论我做什么或放入什么test.html,它总是空的.

Hik*_* G. 8

在内部ngAfterViewInit(),可能还没有加载test.html iframe.

这可以使用(load)="yourLoadFunction()"iframe喜欢的指令来破坏<iframe (load)="yourLoadFunction()"></iframe>

如果您随后将代码ngAfterViewInit()移入yourLoadFunction(),则应该可以正常工作.