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软件安装包(透视)hhpoker万能辅助器(本来是真的有挂)-哔哩哔哩1、在...
透视app!wpk软件是正规的... 透视app!wpk软件是正规的吗(透视)wpk透视工作室(一贯真的是有透视)-哔哩哔哩进入游戏-大厅...
透视攻略!德普之星有透视辅助吗... 透视攻略!德普之星有透视辅助吗(透视)德普之星私人局透视(确实真的有脚本)-哔哩哔哩亲,关键说明,德...
透视工具!wepoker模拟器... 透视工具!wepoker模拟器哪个(透视)wepoker国外版透视(一贯是真的有透视)-哔哩哔哩在进...
透视工具!wejoker黑侠辅... 透视工具!wejoker黑侠辅助器(透视)wepoker有没有机器人(竟然一直都是有挂)-哔哩哔哩1...
透视神器!hhpoker辅助挂... 透视神器!hhpoker辅助挂(透视)hhpoker到底可以作必弊码(原来一直总是有挂)-哔哩哔哩1...
透视神器!模拟器打开hhpok... 透视神器!模拟器打开hhpoker(透视)hhpoker免费透视脚本(切实有透视)-哔哩哔哩1、首先...
透视攻略!hh poker软件... 透视攻略!hh poker软件(透视)hhpoker德州机器人(原来一直总是有透视)-哔哩哔哩1、很...
透视软件!潮汕激k辅助(辅助)... 透视软件!潮汕激k辅助(辅助)新九五辅助微信脚本(其实存在有挂)-哔哩哔哩一、新九五辅助微信脚本可以...
透视脚本!aapoker脚本怎... 透视脚本!aapoker脚本怎么用(透视)aapoker怎么拿好牌(一贯一直都是有透视)-哔哩哔哩1...