将 HTML 附加到 iframe

我想将 HTML 元素添加到 iframe,但每次检查源代码时,都没有添加任何内容。


我的代码如下:


HTML


<div class="canvas-wrapper">

  <iframe class="canvas" #canvas></iframe>

</div>

打字稿


import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';


@Component({

  selector: 'app-canvas',

  templateUrl: './canvas.component.html',

  styleUrls: ['./canvas.component.scss'],

})

export class CanvasComponent implements OnInit {

  @ViewChild('canvas') canvas: ElementRef;


  ngOnInit(): void {

    this.addHtml();

  }


  addHtml(): void {

    const canvas = this.canvas.nativeElement.contentDocument;

    canvas.appendChild('<h1>TEST CONTENT</h1>');

  }

}


aluckdog
浏览 173回答 1
1回答

慕哥6287543

你应该使用另一个钩子:ngAfterViewInitimport { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';@Component({&nbsp; selector: 'app-canvas',&nbsp; templateUrl: './app.component.html',})export class CanvasComponent implements AfterViewInit {&nbsp; @ViewChild('canvas') canvas: ElementRef<HTMLFrameElement>;&nbsp;&nbsp;&nbsp; ngAfterViewInit(): void {&nbsp; &nbsp; this.addHtml();&nbsp; }&nbsp; addHtml(): void {&nbsp; &nbsp; const canvas = this.canvas.nativeElement.contentWindow.document.body;&nbsp; &nbsp; const el = document.createElement('h1');&nbsp; &nbsp; el.innerHTML = `Hello world`;&nbsp; &nbsp; canvas.appendChild(el);&nbsp; }}export default CanvasComponent;你也可以使用@ViewChild('canvas', {static: true}) canvas: ElementRef<HTMLFrameElement>;并访问它ngOnInit(){&nbsp; &nbsp; this.addHtml();&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript