【问题标题】:Not able to show graph on click of a button单击按钮时无法显示图表
【发布时间】:2020-10-19 12:18:20
【问题描述】:

点击时不显示图表。我有

我有两个子组件

  1. 用于显示员工列表的数据组件
  2. 用于显示员工各自评分的评分组件

我已将“图形代码”放入 Rating 组件的“ngOnInit”函数中,单击按钮位于 Data 组件中,借助事件发射,我试图将布尔值从 Data 传递给 Rating 。 正如您在下面的 rating.component.html 中看到的那样,如果标志值变为 true,则显示图表。但即使 flag 变为 true,图形也不可见。

数据组件

import { DataService } from './../../services/data.service';
import { Component, OnInit, Output, EventEmitter} from '@angular/core';



@Component({
  selector: 'app-data',
  templateUrl: './data.component.html',
  styleUrls: ['./data.component.css'],
})
export class DataComponent implements OnInit {
  users: { name: string; city: string }[] = [];
  visible = false;
  @Output() show  = new EventEmitter();
  constructor(private dataSerivce: DataService) {}

  ngOnInit(): void {
   this.users = this.dataSerivce.getEmployees();
  }
  toggle() {
    this.visible = !this.visible;
    if (this.visible) {
      console.log('enter');
      this.show.emit(this.visible);
    } else {
      this.show.emit(null);
    }
  }

}

评分组件


import { Rating } from './../../../../models/rating.model';
import { DataService } from 'src/app/services/data.service';
import { Component, OnInit, Input, OnChanges, SimpleChanges} from '@angular/core';
import {Chart} from '../../../../node_modules/chart.js';

@Component({
  selector: 'app-rating',
  templateUrl: './rating.component.html',
  styleUrls: ['./rating.component.css']
})
export class RatingComponent implements OnInit ,OnChanges{

   rating: Rating[] = [];
   @Input() flag = false;


  constructor(private dataService: DataService) { }

  ngOnInit() {
    console.log('init');
    var myChart= new Chart('myChart', {
      type: 'bar',
      data: {
          labels: ['Technical', 'Communication', 'Experience', 'Leadership'],
          datasets: [{
              label: 'skill scores',
              data: [10,15, 16, 22],
              backgroundColor: [
                  'rgba(255, 99, 132, 0.2)',
                  'rgba(54, 162, 235, 0.2)',
                  'rgba(255, 206, 86, 0.2)',
                  'rgba(75, 192, 192, 0.2)'

              ],
              borderColor: [
                  'rgba(255, 99, 132, 1)',
                  'rgba(54, 162, 235, 1)',
                  'rgba(255, 206, 86, 1)',
                  'rgba(75, 192, 192, 1)'

              ],
              borderWidth: 1
          }]
      },
      options: {
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero: true
                  }
              }]
          }
      }
  });
  }

  ngOnChanges(changes: SimpleChanges){
       console.log('first time');

  }

  private getRatings($event){

       this.dataService.getRating().subscribe(res =>{
           this.rating.push(res);
       });
  }



}

评价 html 代码

<div style="height:40%;width:40%;" class="center" *ngIf ="flag" >
  <canvas
  class="chart chart-bar"
  chart-data="dataChart" id  = "myChart"></canvas>
</div>

【问题讨论】:

  • 我认为您在问题的 HTML 部分中为 RatingsComponent 发布了相同的代码。你能编辑一下吗?

标签: html angular typescript


【解决方案1】:

虽然chart.js 选项可能是正确的,但RatingComponent 中的当前代码并未将chart.js 选项引用到任何特定的DOM Element。这可能是图表未呈现的原因之一。

ChartJS 需要一个 DOM 元素 reference 来渲染图表。

例如:

HTML 模板:

<div #barchart class="barChart"><d/iv>

评级组件:

import { Component, OnInit, ViewChild } from '@angular/core';
import { Chart } from 'chart.js';

  @Component({
    ...
  })

  export class RatingComponent implements OnInit {

    @ViewChild('barchart') private chartRef;
    chart: any;


    ngOnInit() {

        // provide reference of the html component to the the Chart Instance.
        this.chart = new Chart(this.chartRef.nativeElement, {
        // insert chart options here
        });
    
    }

}

或者

查看您的更新后,我认为导致问题的部分是您没有将所需的数据传递给 canvas 组件。

根据ChartJS的文档。

HTML 代码:

<div>
  <div style="display: block">
    <canvas baseChart
            [datasets]="barChartData"
            [labels]="barChartLabels"
            [options]="barChartOptions"
            [legend]="barChartLegend"
            [chartType]="barChartType">
    </canvas>
  </div>
</div>

组件

import { Component, OnInit } from '@angular/core';@Component({
  selector: 'app-my-bar-chart',
  templateUrl: './my-bar-chart.component.html',
  styleUrls: ['./my-bar-chart.component.css']
})

export class MyBarChartComponent implements OnInit {  constructor() { }        

    public barChartOptions = {
        scaleShowVerticalLines: false,
        responsive: true
    };  
    public barChartLabels = ['2006', '2007', '2008', '2009', '2010', '2011',    '2012'];
    public barChartType = 'bar';
    public barChartLegend = true;  public barChartData = [
      {data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
      {data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'}
    ];  

  ngOnInit() {
  }}

【讨论】:

  • 只有在 html 中存在 ngIf 条件时才呈现图表,删除它后才有效。但是一直想不通,为什么会这样???对此有任何想法
  • 这是因为在ngIf的情况下组件无法找到对DOM元素的引用,请尝试ngShow而不是ngIf
  • ng-show(及其兄弟ng-hide)通过添加CSS display: none 样式来切换元素的外观。另一方面,ng-if 实际上在条件为假时从 DOM 中删除元素,并且仅在条件变为真时才将元素添加回来
  • 完全正确,但是当条件为真时,ng if 应该将元素添加到 DOM。正确的 ???还是我错过了什么???
  • ngShow 不起作用,图表现在一直可见。虽然与 ng show 相关,但我发现了另一个有效的属性 [hidden]。所以感谢您的帮助@DhruvShah
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 2012-04-28
  • 1970-01-01
  • 2022-01-05
  • 2012-07-30
相关资源
最近更新 更多