首页 > 解决方案 > 将 HTML 附加到 iframe

问题描述

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

我的代码如下:

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>');
  }
}

标签: javascriptangular

解决方案


你应该使用另一个钩子: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();
  }

推荐阅读