달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2017. 11. 30. 14:29

ionic2, Angular에서 Chart.js 사용법2 개발/Chart.js2017. 11. 30. 14:29

반응형

 

그냥 오리지널 Chart.js를 ionic2에서도 사용할 수 있는 방법이 없는 줄 알았는데.. 있었다.

이 방법이 더 웹에서 사용하던 Chart.js 방법과 유사하기 때문에

앞으로 나는 이 방법을 더 쓰게 될 것 같다.

 

사용 방법은 다음과 같다.

 

1. npm을 사용하여 chart.js를 설치한다.

$ npm  install chart.js --save

 

2. html 파일을 작성한다.

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
   <ion-card>
      <ion-card-content>
        <canvas #chartCanvas></canvas>
      </ion-card-content>
   </ion-card>
</ion-content>

 

3. ts 파일을 작성한다.

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

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild('chartCanvas') chartCanvas;
  chart: any;
  ionViewDidLoad() {
        this.chart = new Chart(this.chartCanvas.nativeElement, {
            type: 'bar',
            data: {
                labels: ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"],
                datasets: [{
                    label: '# of Votes',
                    data: [
                        Math.random(),
                        Math.random(), 
                        Math.random(), 
                        Math.random(), 
                        Math.random(), 
                        Math.random()
                      ],
                    backgroundColor: [
                        'Red',
                        '#FFA500',
                        '#FFFF00',
                        'rgba(50, 205, 50, 1)',
                        'Blue',
                        'rgb(128, 0, 128)'
                    ]
                }]
            },
            options: {

            }
        });
  }
}

 

- web과 다른 점은 canvas의 context를 $('#chartCanvas').get(0).getContext("2d")가 아닌 this.chartCanvas.nativeElement로 가져온다는 것이다.

- 색깔은 보다시피 여러 가지 방법으로 정할 수 있다. 원하는 방법으로 쓰면 될 듯.

 

4. run을 하면 다음과 같은 차트가 그려진 것을 볼 수 있다.

$ cordova run android

 

 

 

 

출처 : https://www.joshmorony.com/adding-responsive-charts-graphs-to-ionic-2-applications/

반응형
:
Posted by 리샤씨