Angular应用程序中的图表和窗口不会自适应大小。
创始人
2024-10-30 15:00:32
0

问题通常是由于未正确定义组件的尺寸所致。如果使用 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 方法动态调整宽度和高

相关内容

热门资讯

透视烘培!wepoker有插件... 透视烘培!wepoker有插件吗(WPK多开)确实有辅助技巧(哔哩哔哩)1.wepoker有插件吗 ...
透视透视挂!微信微乐游戏辅助脚... 透视透视挂!微信微乐游戏辅助脚本,微信微乐自建房脚本下载(透视)切实是有辅助方法(哔哩哔哩)进入游戏...
透视妙招!wepoker提高好... 透视妙招!wepoker提高好牌率(WePoKer辅助挂)一贯真的是有辅助技巧(哔哩哔哩)1、下载好...
透视肯定!微信微乐游戏辅助脚本... 透视肯定!微信微乐游戏辅助脚本,微信微乐辅助器使用教程(透视)都是真的是有辅助挂(哔哩哔哩)一、可以...
透视模板!hhpoker到底可... 您好,hhpoker到底可以作必弊码这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704...
现有说明如下!微乐小程序黑科技... 现有说明如下!微乐小程序黑科技,微乐自建房辅助工具(透视)都是存在有辅助工具(哔哩哔哩)1、进入到是...
透视透视!微乐小程序黑科技,微... 透视透视!微乐小程序黑科技,微乐自建房免费辅助入口在哪里(透视)其实真的有辅助攻略(哔哩哔哩)1、辅...
透视阶段!wepoker透视破... 透视阶段!wepoker透视破解版(HHpoker机器人)真是真的是有辅助软件(哔哩哔哩)1、操作简...
透视策略!aapoker怎么选... 透视策略!aapoker怎么选牌(WePoKer脚本)原来是真的有辅助软件(哔哩哔哩)1、aapok...
出乎意料的是!微乐小程序黑科技... 出乎意料的是!微乐小程序黑科技免费,微信小程序微乐为什么老输(透视)一贯是真的辅助app(哔哩哔哩)...