问题通常是由于未正确定义组件的尺寸所致。如果使用 Chart.js 等外部图库,则需要定义图表和窗口组件的宽度和高度。以下示例代码为在 Angular 应用程序中使用 Chart.js 的组件提供了解决方案:
HTML 文件:
TypeScript 文件:
import { Component, ElementRef, ViewChild } from '@angular/core';
import { Chart } from 'chart.js';
@Component({
selector: 'app-chart',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.css']
})
export class ChartComponent {
@ViewChild('myChart') private chartRef: ElementRef;
private chart: any;
chartWidth: number;
chartHeight: number;
constructor() {
this.chartWidth = 500;
this.chartHeight = 300;
}
ngAfterViewInit() {
this.chart = new Chart(this.chartRef.nativeElement, {...});
this.updateChartDimensions();
}
private updateChartDimensions() {
const width = this.chartRef.nativeElement.offsetWidth;
const height = this.chartRef.nativeElement.offsetHeight;
if (width && height) {
this.chartWidth = width;
this.chartHeight = height;
this.chart.resize();
}
}
}
以上代码示例中,我们在 HTML 文件中使用了一个 div 元素,用于包装 canvas 元素,从而使其充满父容器。接下来,我们将 Canvas 元素绑定到通过 ViewChild 装饰器引用的元素。
在构造函数中,我们定义了图表和窗口组件的宽度和高度,这些属性将用于在根据 ClassName 加载组件时设置元素的大小时进行调整。在 ngAfterViewInit 方法中,我们实例化图表对象,并使用 updateChartDimensions 方法动态调整宽度和高