javascript - 将 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>');
}
}
解决方案
你应该使用另一个钩子: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();
}
推荐阅读
- php - 未找到 Laravel 自定义作曲家 libaray 类
- tags - 如何在 Runner 类中对 Cucumber 标签进行排序
- python - 在方法中调用函数
- android - 带有 XML 的 BottomNavigationView 设计 *没有以编程方式
- excel - 如何在 VBA 中打开具有可变日期名称的文件?
- twilio - 入站 Twllio SMS 触发 LogicApp
- botframework - 有没有办法从 Stack Overflow 中提取共享相同标签的问题和答案?
- azure - 我可以通过设备令牌获取注册吗?
- javascript - 使用异步等待获取失败时如何捕获状态代码
- javascript - 如何在页面加载时折叠所有选项卡?