본문 바로가기

프레임워크/Angular

Angular 에 그래프 삽입하기


1. 필요한것

npm, angular, chart.js, ng2-charts

npm 은 필요한 내용을 설치하기 위해서 필요하다.

angular 는 프레임워크

chart.js 는 JavaScript library

ng2-charts 는 차트(그래프)를 사용하기 위해.. 오픈소스 라이브러리라고 하는데. chart.js 를 쓰기위해 필요한듯


2. 설치 순서  (차트를 사용하는 방법 .js ng2 차트가있는 각도에서 | 디지털오션 (digitalocean.com))

1). 새 프로젝트 example 를 만든다.

     npx @angular/cli new example 

- --style=css, --routing=false, --skip-tests 을 뒤에 붙이면

  스타일, 라우팅 설정과 테스트용 파일인 spect 설치를 건너뛸 수 있다.

     ? npm  vs  npx ([ReactJS] npm과 npx의 용어정리 및 차이점 :: 꾸밈없는 (tistory.com))

        요약하자면 npm 은 설치, npx 는 설치 + 실행

 

2). 새로 만든 프로젝트에 접근하여, chart.js 를 설치한다.

    npm install chart.js@2.9.4 ng2-charts@2.4.2 

 

3). 설치 후, angular.json 을 열어서 코드를 수정한다.

{
  // ...
  "projects": {
    "angular-chartjs-example": {
      // ...
      "architect": {
        "build": {
          // ...
          "options": {
            // ...
            "scripts": [
              "node_modules/chart.js/dist/Chart.min.js" 
            ],
            "allowedCommonJsDependencies": [
              "chart.js"
            ] 
          },

 

4). app.module.ts 파일에 ChartModule 을 import 한다.


3. 차트 만들기

1). 차트를 만들 캔버스를 html 파일에 만든다.

<div>
  <canvas

      baseChart >
  </canvas>
</div>

 

2). 차트의 구성요소를 만든다.

    [chartType]="'line'" / 차트 타입

    - bar, doughnut, horizontalBar, line, pie, polarArea, radar

    [legend]="true" / 데이터 설명

    [datasets]="chartData" / 데이터 정보

    [labels]="chartLabels" / X축 데이터

    [options]="chartOptions" / 차트에 대한 옵션

 

3). ts 파일에서 상세 설정

  chartData = [
    {
      data: [10, 50, 200, 300],
      label: 'Account A'
    },
    {
      data: [100, 150, 200, 300],
      label: 'Account B'
    },
    {
      data: [50, 250, 280, 290],
      label: 'Account C'
    }
  ];

  chartLabels = [
    '김가가',
    '김나나',
    '김다다',
    '김라라'
  ];


처음에 설정할때 너무 해맸다.

'프레임워크 > Angular' 카테고리의 다른 글

material 사용하기  (0) 2022.10.05
Apex Chart  (0) 2022.09.20
객체지향_1, Class, Object, Instance  (0) 2022.09.20
CreatComponent  (0) 2022.09.16
LifeCycle  (0) 2022.09.14