Sunday, August 18, 2019

How to Create a Bar Chart in Angular

How to Create a Bar Chart in Angular

Step 1. Create new App in Angular
ng new pointchartangular
Step 2. install libary
npm i devextreme-angular
npm install stream --save
Install the devextreme and devextreme-angular npm packages:
npm install devextreme@19.1 devextreme-angular@19.1 --save --save-exact
Step 3. Coppy code below in app.component.html
<dx-chart
    id="chart"
    [dataSource]="dataSource">
    <dxi-series
        argumentField="day"
        valueField="oranges"
        name="My oranges"
        type="bar"
        color="#00FF82">
    </dxi-series>
</dx-chart>
Step 4. Create service/Service have name service.ts
@Injectable()
export class Service {
    getData(): Data[] {
        return data;
    }
}
in file service.ts you create a class Data below.
export class Data {
    day: string;
    oranges: number;
}
and in service.ts you get data in class Data
let data: Data[] = [{
    day: "Monday",
    oranges: 3
}, {
    day: "Tuesday",
    oranges: 2
}, {
    day: "Wednesday",
    oranges: 3
}, {
    day: "Thursday",
    oranges: 4
}, {
    day: "Friday",
    oranges: 6
}, {
    day: "Saturday",
    oranges: 11
}, {
    day: "Sunday",
    oranges: 4
}];
Step 5. in app.compont.scss
::ng-deep #chart {
    height: 440px;
}
Step 6. in app.component.ts
import { Component } from '@angular/core';
import { Data } from '@angular/router';
import { Service } from './Service/service.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'barchartangular';
  dataSource: Data[];
  constructor(service: Service) {
      this.dataSource = service.getData();
  }
}
Note :  you add DxChartModule and Service in app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {DxChartModule} from 'devextreme-angular';
import { Service } from './Service/service.service';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    DxChartModule,
    AppRoutingModule
  ],
  providers: [ Service],
  bootstrap: [AppComponent]
})
export class AppModule { }
You can download project at github


No comments:

Post a Comment