简体   繁体   English

使用打字稿单击删除画布元素

[英]Remove canvas element on click with typescript

I am new to typescript and what i am trying is, to remove canvas element from the div. 我是TypeScript的新手,而我正在尝试的是从div中删除canvas元素。 So here is my HTML code. 这是我的HTML代码。

<div class="chart">
    <canvas id="nav-chart"></canvas>
</div>

on click removing the canvas element using id nav-chart . 单击以使用id nav-chart删除canvas元素。 So here my JS code inside the onclick function 所以这是我在onclick函数中的JS代码

const elem: HTMLElement = document.getElementById('nav-chart')
if (elem) {
   elem.parentElement.removeChild(elem)
}

While trying this it throws the error saying at the line 尝试此操作时,它会抛出错误提示
const elem: HTMLElement = document.getElementById('nav-chart')

TS2322: Type 'HTMLElement | null' is not assignable to type 'HTMLElement'.
  Type 'null' is not assignable to type 'HTMLElement'.

and in this line elem.parentElement.removeChild(elem) 在这一行中elem.parentElement.removeChild(elem)

TS2531: Object is possibly 'null'.

I found the solution first we have to declare the element type with HTMLElement | null 我首先找到了解决方案,我们必须使用HTMLElement | null声明元素类型HTMLElement | null HTMLElement | null

const elem: HTMLElement | null = document.getElementById('nav-chart')

and inside the condition. 在病情里面

if (elem) {
      elem.parentElement && elem.parentElement.removeChild(elem)
}

That's not how Angular works. Angular并不是这样工作的。

showCanvas = true;
<div class="chart" (click)="showCanvas = false">
    <canvas id="nav-chart" *ngIf="showCanvas"></canvas>
</div>

I highly suggest you to learn the concepts of Angular before using it to code. 我强烈建议您在使用Angular进行编码之前,先学习一下Angular的概念。 Most of the developers do as you did, and most of the time, they end up misusing the framework. 大多数开发人员都像您一样做,并且大多数时候,他们最终会滥用框架。

Spend all the time you need on learning the framework philosophy, THEN learn to use it ! 将所有时间花在学习框架哲学上, 然后学习使用它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM