gab*_*ela 14 javascript iframe angular
我在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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果我评论构造函数的代码并启动应用程序,它将编译并正确运行.然后我取消注释并完全运行(按钮出现在iframe中).
如果我取消代码然后启动应用程序(npm start)我有编译错误消息:
类型'HTMLElement'上不存在属性'contentWindow'
.
我还尝试了将costructor的代码放入ngOnInit(),ngAfterContentInit(),ngAfterViewInit()的替代方法,但错误仍然存在.
Gün*_*uer 20
在执行构造函数时,DOM中不存在该模板
请改用
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'component-iframe',
template: '<iframe #iframe></iframe>'
})
export class ComponentIframe {
@ViewChild('iframe') iframe: ElementRef;
ngAfterViewInit() {
let content = '<button id="button" class="button" >My button </button>';
let doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow;
doc.open();
doc.write(content);
doc.close();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 16
用这个:
let iframe = document.getElementById('iframe') as HTMLIFrameElement
Run Code Online (Sandbox Code Playgroud)
我通过以下方式解决了这个问题:
const element: HTMLIFrameElement = document.getElementById('iframe') as HTMLIFrameElement;
const iframe = element.contentWindow;
if (iframe !== null) {
...
}
Run Code Online (Sandbox Code Playgroud)