1 回答
TA贡献1831条经验 获得超10个赞
你应该使用另一个钩子:ngAfterViewInit
import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-canvas',
templateUrl: './app.component.html',
})
export class CanvasComponent implements AfterViewInit {
@ViewChild('canvas') canvas: ElementRef<HTMLFrameElement>;
ngAfterViewInit(): void {
this.addHtml();
}
addHtml(): void {
const canvas = this.canvas.nativeElement.contentWindow.document.body;
const el = document.createElement('h1');
el.innerHTML = `Hello world`;
canvas.appendChild(el);
}
}
export default CanvasComponent;
你也可以使用
@ViewChild('canvas', {static: true}) canvas: ElementRef<HTMLFrameElement>;
并访问它
ngOnInit(){
this.addHtml();
}
添加回答
举报