0

Angularでchart.jsを使用してます。

これは、動くときもありますが、
初期表示時には動かず、
ウィンドウサイズを変えたときなどには表示されます。

初期表示時に描画したいのですが、
どうすればいいでしょうか。

1⃣画面の初期表示時、グラフのデータが描画されません
初期表示で動かない

2⃣ウィンドウサイズを変えると描画されます。
ウィンドウサイズを変えると表示される

import { Component, OnInit ,AfterViewInit,DoCheck,ViewChild} from '@angular/core';
import { AngularFireDatabase, AngularFireList, SnapshotAction } from '@angular/fire/database';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Poll } from '../class/poll';
import * as echarts from "echarts";
import { EChartsOption } from 'echarts';
import { Chart, ChartData, ChartOptions } from 'chart.js';

@Component({
  selector: 'ac-poll',
  templateUrl: './poll.component.html',
  styleUrls: ['./poll.component.css']
})
export class PollComponent implements OnInit , AfterViewInit, DoCheck{

  polls$: Observable<Poll[]>;
  pollsRef: AngularFireList<Poll>;

  // sources:any[][] = new Array();
  chartOption: EChartsOption = {};

  //chart.js
  data: ChartData;
  options: ChartOptions;
  context;
  chart: Chart;

  @ViewChild("myCanvas") myCanvas;

  constructor(
  private db: AngularFireDatabase
  ) {
    this.pollsRef = db.list('/polls/poll/count');
  }



  addCount(poll:Poll):void{
    const { key, count } = poll;
    this.pollsRef.update(key, new Poll(key,count+1));

    this.drawCanvas();

  }


  ngOnInit(): void {
    this.polls$ = this.pollsRef.snapshotChanges()
    .pipe(
      map((snapshots: SnapshotAction<Poll>[]) => {
        return snapshots.map(snapshot => {
          const key = snapshot.payload.key;
          const value = snapshot.payload.val();
          const valueNum = Number(value);
          return new Poll(value.key,value.count)

        });
      })
    );

    // this.context = document.getElementById('myChart');
    // if(this.context != undefined){
    //   this.drawCanvas();
    // }

    if(this.myCanvas === undefined){

    }else{
      let canvas = this.myCanvas.nativeElement;
      this.context = canvas.getContext("2d");
      this.drawCanvas();
    }
  }


  ngAfterViewInit(){
    // canvasを取得
    // this.context = document.getElementById('myChart');
    let canvas = this.myCanvas.nativeElement;
    this.context = canvas.getContext("2d");

    this.drawCanvas();
  }

  ngDoCheck(): void {
    // this.drawCanvas(); //ここうまく動かない

  }

  drawCanvas(){

      //labelsとdata用の配列を取得
      let labelData = [];
      let dataItems = [];

      this.polls$ = this.pollsRef.snapshotChanges()
      .pipe(
        map((snapshots: SnapshotAction<Poll>[]) => {
          return snapshots.map(snapshot => {
            const key = snapshot.payload.key;
            const value = snapshot.payload.val();
            const valueNum = Number(value);

            //グラフ
            labelData.push(value.key);
            dataItems.push(value.count);

            return new Poll(value.key,value.count)

          });
        })
      );

      console.log(labelData)
      console.log(dataItems)

      //contextが存在してたら
      const ctx = this.context;

      if(ctx){
      // チャートがすでに存在してたら破棄する
      if (this.chart) {
        this.chart.destroy();
      }
      // チャートの作成
      this.chart = new Chart(this.context, {
        type: 'horizontalBar',
        data: {
          //labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
          labels: labelData,
          datasets: [{
            label: '# of Votes',
            // data: [12, 19, 3, 5, 2, 3],
            data: dataItems,
            borderWidth: 1
          }]
        },
        options: {
          scales: {
            xAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
          }
        }
      });
    };

    console.log(this.chart)

    this.chart.resize()
    this.chart.update()
  }

}
<p>poll works!</p>

<section class="poll">
  <div class="poll-list">
    <div
      *ngFor="let poll of polls$ | async"
      class="list-group-item list-group-item-action flex-column align-items-start border-0"
    >
      <div class="media">
        <div
          (click)="addCount(poll);"
          class="media-body">
          <div>{{ poll.key }}</div>
          <div>{{ poll.count }}</div>
        </div>
      </div>
    </div>
  </div>
</section>
<!--
<section class="pollView">
  <div id="chart" echarts [options]="chartOption" class="demo-chart"></div>
</section>
-->
<div>
  <canvas #myCanvas></canvas>
</div>
<p>poll works!</p>

0

この質問に回答するには、ログインする必要があります。

のタグが付いた他の質問を参照する。