typescript - 如何在 Angular 中清空 div 内容?(Angular 7)
我已经尝试过
let graphDiv = document.querySelector('div#graphDiv').innerHTML;
graphDiv.clear();
or
graphDiv.destroy();
在谷歌搜索中没有找到答案。我的 div 内容是随机生成的(因此我使用 Math.random() 来预先填充图表)。我想通过组件清除 div 内容,而不是通过 HTML 模板。
答案#1
在 Angular 中,不推荐使用 JavaScript 自身的技术。推荐使用 Angular 功能进行 DOM 操作。
以下是我进行 DOM 操作的方法。
(我在下面的代码中使用了 @Component,但建议使用 @Directive 来完成渲染任务)
(我也是初学者在学习Angular。如果有任何错误或更好的解决方案,请分享)
A. 文件结构作为组件
- graph.component.html
- 图表.组件.ts
B. Angular 代码
B-1. 在 graph.component.html 中
<div #graphDiv></div>
B-2. 在 graph.component.ts 中
import { Component, Renderer2, ViewChild, ElementRef } from '@angular/core';
@Component({
templateUrl: './graph.component.html'
})
export class GraphComponent {
@ViewChild("graphDiv") graphDiv: ElementRef;
constructor(private renderer:Renderer2) {
}
clearDiv() {
let valueYouWantToPut = "cleared";
this.renderer.setProperty(this.graphDiv.nativeElement, 'innerHTML', valueYouWantToPut)
}
}
如需进一步学习,请参考我所使用的以下网站:https://indepth.dev/posts/1336/how-to-do-dom-manipulation-properly-in-angular
答案#2
你可以这样做:
document.querySelector('div#graphDiv').innerHTML = "";
(虽然评论中指出的方法会更好)
