1 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊
你應(yīng)該使用另一個(gè)鉤子: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();
}
添加回答
舉報(bào)