【发布时间】:2016-11-22 07:08:04
【问题描述】:
我在 angular2 组件中有一个 iframe,我正在尝试通过访问 contentWindow 来更改 iframe 的内容。
iframe 应该包含一个简单的按钮。
我的代码:
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 中)。
如果我取消代码然后启动应用程序 (npm start) 我有编译错误消息:
“HTMLElement”类型上不存在属性“contentWindow”
.
我还尝试了将构造函数的代码放入 ngOnInit()、ngAfterContentInit()、ngAfterViewInit() 的替代方法,但错误仍然存在。
【问题讨论】:
标签: javascript iframe angular