AngularNGXChart在加载时未正确适应父容器大小
创始人
2024-10-28 18:31:17
0

使用ViewChild和ngAfterViewInit钩子对图表进行重新渲染。

在组件的HTML文件中,设置一个包含图表的div,并使用ngStyle指令将其大小设置为父级容器的大小:

在组件的TS文件中,使用ViewChild和ngAfterViewInit来获取父级容器的大小,并在重新渲染图表时将其应用于ngx-charts组件:

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { ChartComponent } from 'ng2-charts';

@Component({
  selector: 'app-my-chart',
  template: '
', styleUrls: ['./my-chart.component.css'] }) export class MyChartComponent implements AfterViewInit { @ViewChild('chartDiv') chartDiv: ElementRef; @ViewChild(ChartComponent) chartComponent: ChartComponent; public pieChartData: number[] = []; public pieChartLabels: string[] = []; public pieChartType = 'pie'; public pieChartOptions: any = { responsive: true }; parentHeight: string; parentWidth: string; ngAfterViewInit() { this.parentHeight = this.chartDiv.nativeElement.parentElement.offsetHeight + 'px'; this.parentWidth = this.chartDiv.nativeElement.parentElement.offsetWidth + 'px'; this.chartComponent.chart.update(); } }

该示例组件显示了一个饼图,将其大小设置为其父级容器的大小。在ngAfterViewInit钩子中,我们使用ViewChild获取chartDiv元素的引用,并使用nativeElement获取其父元素的高度和宽度。然后,我们更新ChartComponent的图表,并在这之后重新渲染。

相关内容

热门资讯

突发!xpoker辅助怎么用(... 突发!xpoker辅助怎么用(透视)内置辅助器大全(确实有辅助辅助器)-哔哩哔哩1)内置辅助器大全免...
围绕透视问题!wepoker私... 围绕透视问题!wepoker私人局开挂视频(透视)随意玩辅助器(一直有辅助平台)-哔哩哔哩1)随意玩...
做出回应!wepoker辅助脚... 做出回应!wepoker辅助脚本(透视)丰城双剑辅助(一贯真的是有辅助app)-哔哩哔哩1、点击下载...
透视免费!wejoker手机版... 透视免费!wejoker手机版透视脚本(透视)友友联盟破解版下载(总是是真的辅助下载)-哔哩哔哩一、...
围绕透视问题!hhpoker辅... 围绕透视问题!hhpoker辅助软件(透视)熊猫辅助技术导航(好像真的是有辅助app)-哔哩哔哩1、...
据了解!hhpoker万能辅助... 据了解!hhpoker万能辅助器(透视)葫芦娃辅助脚本(总是真的是有辅助安装)-哔哩哔哩1、葫芦娃辅...
透视透视挂!hhpoker必备... 透视透视挂!hhpoker必备开挂(透视)牛总管辅助方法(好像真的是有辅助下载)-哔哩哔哩1、让任何...
透视脚本!we-poker软件... 透视脚本!we-poker软件(透视)微乐小程序有脚本吗(一直真的有辅助安装)-哔哩哔哩该软件可以轻...
据统计!hhpoker德州透视... 据统计!hhpoker德州透视(透视)新九方辅助(其实存在有辅助下载)-哔哩哔哩该软件可以轻松地帮助...
为切实保障!pokemmo手机... 为切实保障!pokemmo手机脚本辅助器(透视)极速猜一猜辅助(真是真的有辅助辅助器)-哔哩哔哩小薇...