我无法在我的一个标签内显示来自ChartJS的图表,其标签组位于对话框内。我遇到的第一个问题是,标签一开始不在DOM中,因此我无法获取画布的上下文。我以某种方式设法克服了这一点:
patient-view.component.html (对话):
<mat-dialog-content>
<div>
<h2 mat-dialog-title class="text-centered fs-16 my-2"><b>{{patientChosen.name}}</b></h2>
</div>
<mat-tab-group animationDuration="0ms" mat-stretch-tabs [selectedIndex]="1" disableRipple (selectedTabChange)="populateDatasets()">
<mat-tab label="Evaluaciones">
<div class="tab-container">
<p class="text-centered fs-14 mt-4">Nada en <b>'Evaluaciones'</b></p>
<p class="text-centered fs-10 mt-1">Se agregará contenido después</p>
</div>
</mat-tab>
<mat-tab label="Datos">
<div class="tab-container">
<p class="text-centered fs-14 mt-4">RUT: {{patientChosen.rut}}</p>
<p class="text-centered fs-10 mt-1">Edad: {{patientChosen.age}} años</p>
<p class="text-centered fs-10 mt-1">Clasificación: CROHN</p>
<p class="text-centered fs-10 mt-1">Se agregará contenido después</p>
</div>
</mat-tab>
<mat-tab label="Evolución"> // <---------------------------# # # # # Here goes the chart
<ng-template matTabContent>
<div class="tab-container">
<mat-card>
<mat-card-header class="bg-primary-color">
<mat-card-title class="text-centered mt-2 c-white">Evolución del paciente</mat-card-title>
<mat-card-subtitle class="text-centered mb-2 c-white">Según cuestionarios HB Corto e IBDQ9</mat-card-subtitle>
</mat-card-header>
<mat-card-content class="text-centered">
<canvas id="myChart" class="m-0-auto" width="700" height="400"></canvas>
</mat-card-content>
</mat-card>
</div>
</ng-template>
</mat-tab>
</mat-tab-group>
</mat-dialog-content>
Patient-view.component.ts
export class PatientViewComponent implements OnInit{
constructor(@Inject(MAT_DIALOG_DATA) public patientChosen: any) { }
ngOnInit(): void {
console.log('Data here: ',this.patientChosen);
}
ngAfterViewInit(){
this.populateDatasets();
}
populateDatasets(){
let weekly_dates = [ '04/05/2020', '11/04/2020', '18/04/2020', '25/05/2020']
let ibdq = Array.from({length: 4}, () => Math.floor(Math.random() * 80));
let hb_short = Array.from({length: 4}, () => Math.floor(Math.random() * 80));
let canvas = <HTMLCanvasElement> document.getElementById('myChart');
let ctx = canvas.getContext('2d');
let chart = new Chart(ctx,{
type: 'bar',
data:{
labels: weekly_dates,
datasets:[
{
label: 'IBDQ9',
type: 'line',
data: ibdq,
backgroundColor: 'rgba(30, 25, 75, 0.6)',
borderColor: 'rgba(30, 25, 75, 0.6)',
fill: false,
},
{
label: 'HB-Corto',
type: 'line',
data: hb_short,
backgroundColor: 'rgba(60, 180, 75, 0.9)',
borderColor: 'rgba(60, 180, 75, 0.9)',
fill: false,
}
]
},
options: {
responsive: false,
scales:{
xAxes:[
{
gridLines: {
display:false,
}
}
],
yAxes:[
{
gridLines: {
display:true,
}
}
],
}
}
})
}
}
通过添加ng-template
并将图表加载到ngAfterViewInit
,我实际上可以显示图表。问题是我仍然遇到相同的错误:
错误TypeError:无法读取null的属性“ getContext”
当我在选项卡之间移动并返回到图表选项卡时,将再次加载图表,这现在不是问题,但是可能是当我从API加载数据时。
有什么方法可以从选项卡html(最初不在DOM上)中获取画布,以及如何在首次进入该选项卡时仅将其加载一次?