【问题标题】:TS2345: Argument of type 'HTMLElement' is not assignable to parameter of type 'ChartItem'TS2345:\'HTMLElement\' 类型的参数不可分配给 \'ChartItem\' 类型的参数
【发布时间】:2022-11-21 14:02:43
【问题描述】:

我正在开发 Angular 仪表板,我发现这个错误不允许我渲染面积图

import { AfterViewInit, Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
import { Chart } from 'chart.js';

@Component({
selector: 'app-widget-area',
templateUrl: './area.component.html',
styleUrls: ['./area.component.scss']
})
export class AreaComponent implements AfterViewInit {


 constructor() {}
 ngAfterViewInit() {
    let elem: HTMLElement;
    const ctx = document.getElementById("myChart") as HTMLElement;
     if (ctx) {
        elem = ctx;
        const myChart = new Chart(elem, {
            data: {
                datasets: [
                    { fill: 'origin' },      // 0: fill to 'origin'
                    { fill: '+2' },         // 1: fill to dataset 3
                    { fill: 1 },             // 2: fill to dataset 1
                    { fill: false },         // 3: no fill
                    { fill: '-2' },          // 4: fill to dataset 2
                    { fill: { value: 25 } }    // 5: fill to axis value 25
                ]
            }
        });
    }
}

并得到这个错误:

TS2345: Argument of type 'HTMLElement' is not assignable to parameter of type 'ChartItem'.
Type 'HTMLElement' is missing the following properties from type 'HTMLCanvasElement': height, width, captureStream, getContext, and 2 more.

我已经尝试了所有互联网的东西,但对我没有任何帮助,有人遇到同样的错误吗? 顺便说一句,这是我的简单 html,我有来自 charjs 的 NgChartModule,但对我没有任何作用

<div>
  <div style="display: block">
  <canvas id="myChart " ></canvas>

  </div>
</div>

【问题讨论】:

标签: html angular typescript charts html5-canvas


【解决方案1】:

Chart类的构造函数将第一个参数(item)作为ChartItem类型,其中ChartItem采用以下类型:

ChartItem: string | CanvasRenderingContext2D | HTMLCanvasElement | { canvas: HTMLCanvasElement } | ArrayLike<CanvasRenderingContext2D | HTMLCanvasElement>

来自here,可以看到用法:

const ctx = document.getElementById('myChart');
const ctx = document.getElementById('myChart').getContext('2d');
const ctx = $('#myChart');
const ctx = 'myChart';
const ctx = document.getElementById("myChart");
if (ctx) {
    const myChart = new Chart(ctx, {
            data: {
                datasets: [
                    { fill: 'origin' },      // 0: fill to 'origin'
                    { fill: '+2' },         // 1: fill to dataset 3
                    { fill: 1 },             // 2: fill to dataset 1
                    { fill: false },         // 3: no fill
                    { fill: '-2' },          // 4: fill to dataset 2
                    { fill: { value: 25 } }    // 5: fill to axis value 25
                ]
            }
        });
}

【讨论】:

  • 谢谢!我试过“任何”; var canvas: any = document.getElementById("myChart"); var ctx = canvas.getContext("2d");
猜你喜欢
  • 2018-08-10
  • 1970-01-01
  • 2018-02-09
  • 2021-05-17
  • 2018-10-19
  • 1970-01-01
  • 2021-08-19
  • 2019-09-24
  • 2017-07-14
相关资源
最近更新 更多