我正在尝试更改 Angular 2 中 iframe 内元素的值。我尝试了很多东西,但始终无法使用 getElementById()
引用项目。 .我有一个测试场景在一种情况下有效,而在另一种情况下无效,这让我更加困惑:
组件.html
<iframe #iframe src="assets/test.html"></iframe>
测试.html
<h1 id="wow">Wow</h1>
工作 typescript (打印<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"));
}
}
非工作 typescript (打印 null
)
export class MyComponent implements AfterViewInit {
@ViewChild('iframe') iframe: ElementRef;
ngAfterViewInit() {
var doc = this.iframe.nativeElement.contentDocument;
console.log(doc.getElementById("wow"));
}
}
问题
我到底怎样才能让第二个正确打印元素?不管我做什么或放什么test.html
,它始终为空。
最佳答案
内部ngAfterViewInit()
,很可能 test.html 尚未加载到 iframe
中还没有。
这可以使用 (load)="yourLoadFunction()"
来颠覆你的指令 iframe
喜欢<iframe (load)="yourLoadFunction()"></iframe>
如果您随后将代码从 ngAfterViewInit()
进入yourLoadFunction()
,它应该可以正常工作。
关于javascript - Angular 2 iframe混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42518370/