【发布时间】:2017-02-28 20:43:09
【问题描述】:
我正在尝试更改 Angular 2 中 iframe 内元素的值。我尝试了很多方法,但始终无法使用 getElementById() 引用项目。我有一个测试场景适用于一种情况,而不是另一种情况,这让我更加困惑:
component.html
<iframe #iframe src="assets/test.html"></iframe>
test.html
<h1 id="wow">Wow</h1>
工作打字稿(打印<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"));
}
}
不工作的打字稿(打印null)
export class MyComponent implements AfterViewInit {
@ViewChild('iframe') iframe: ElementRef;
ngAfterViewInit() {
var doc = this.iframe.nativeElement.contentDocument;
console.log(doc.getElementById("wow"));
}
}
问题
我怎么才能让第二个正确打印元素?无论我做什么或我在test.html 中输入什么,它始终为空。
【问题讨论】:
标签: javascript html angular iframe