I have created a line chart using c3.js and angular 2.But i am getting a unwanted black area in line chart.It's working more likely chart with filled area.I am trying to override it's css property..."fill-opacity". but it's not working.Give me a solution.enter image description here
Due to c3 lib CSS is missing. CSS file for C3 chart .
https://rawgit.com/masayuki0812/c3/master/c3.css.
copy past css into your bar-chart.component.css and add encapsulation in decorator as shown in e.g.
It will definitely work :->
import { Component, ViewEncapsulation, OnInit } from '#angular/core';
import * as c3 from 'c3';
import * as d3 from 'd3';
#Component({
selector: 'app-bar-chart',
templateUrl: './bar-chart.component.html',
styleUrls: ['./bar-chart.component.css'], //copy and paste css here
encapsulation: ViewEncapsulation.None //add this line in your component
})
export class BarChartComponent implements OnInit {
jsonData : any[] = [];
jsonKeys : any = {};
jsonAxis : any = {};
constructor() { }
ngOnInit() {
this.jsonData = [
{name: 'www.site1.com', upload: 200, download: 150, total: 400},
{name: 'www.site2.com', upload: 100, download: 300, total: 400},
{name: 'www.site3.com', upload: 300, download: 200, total: 500},
{name: 'www.site4.com', upload: 400, download: 100, total: 500},
];
this.jsonKeys = {
x: 'name', // it's possible to specify 'x' when category axis
value: ['upload', 'download'],
};
this.jsonAxis = {
x : {
type : 'category'
}
};
let chart = c3.generate({
bindto: '#chart',
data: {
json: this.jsonData,
keys: this.jsonKeys,
},
axis: this.jsonAxis,
});
}
}
Related
I've developed a website in Angular 14 that treat about cryptocurrencies using the CoinGecko API.
I wanted to display a chart for every cryptocurrency on a specific page using chart.js and ng2-charts.
I've parsed the data sent by the API and used it in my chart but it is not showing the line chart expected.
Here is a service that is getting the data from the API and parse it:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import {map, Observable, Subscription } from 'rxjs';
#Injectable({
providedIn: 'root',
})
export class SingleCryptoGraphService {
subscription: Subscription;
doubletab: any = {
date : Array<string>(),
price: Array<number>(),
};
constructor(private httpClient: HttpClient) {
this.subscription = Subscription.EMPTY;
}
HistoricalChart(id: string, currency: string, days: number): Observable<any> {
return this.httpClient
.get<any[]>(
'https://api.coingecko.com/api/v3/coins/'+id+'/market_chart?vs_currency='+currency+'&days='+days+'&interval=daily').pipe(
map( (obj: any) => obj['prices']),
map((tab: any[]) => {
const res = [];
for (let i = 0; i < tab.length; i++) {
this.doubletab.date.push(this.getDate(tab[i][0]));
this.doubletab.price.push(this.convertToNumber(tab[i][1]));
}
console.log(this.doubletab);
return this.doubletab;
}
)
);
}
getDate = (date: number) : string => {
let d = new Date(date)
let day = d.getDate()
let month = d.getMonth() + 1
let year = d.getFullYear()
return day + "/" + month + "/" + year
}
convertToNumber = (str: string) : number => {
return Number(str)
}
}
Here is the chart component TypeScript:
import { Component, OnDestroy, OnInit, Input, ViewChild } from '#angular/core';
import { SingleCryptoGraphService } from '../single-crypto-graph.service';
import { Subscription } from 'rxjs';
import { Chart, ChartConfiguration, ChartEvent, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
#Component({
selector: 'app-crypto-graph',
templateUrl: './crypto-graph.component.html',
styleUrls: ['./crypto-graph.component.css']
})
export class CryptoGraphComponent implements OnInit, OnDestroy {
subscription3: Subscription
chartInfoTabs: any = {
date: Array<string>(),
price: Array<number>(),
}
#Input() id = ''
constructor(private SingleCryptoGraphService:SingleCryptoGraphService) {
this.subscription3 = Subscription.EMPTY;
this.id = "none";
}
ngOnInit(): void {
this.subscription3.unsubscribe()
this.subscription3 = this.SingleCryptoGraphService.HistoricalChart(this.id,"eur",30).subscribe(
(data) => {
this.chartInfoTabs.date = data.date;
this.chartInfoTabs.price = data.price;
}
);
}
ngOnDestroy() {
this.subscription3.unsubscribe()
}
public lineChartData: ChartConfiguration['data'] = {
datasets: [{
data: this.chartInfoTabs.price,
label: this.id,
backgroundColor: 'rgba(148,159,177,0.2)',
borderColor: 'rgba(148,159,177,1)',
pointBackgroundColor: 'rgba(148,159,177,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(148,159,177,0.8)',
fill: 'origin',
}],
labels: this.chartInfoTabs.date,
}
public lineChartOptions: ChartConfiguration['options'] = {
elements: {
line: {
tension: 0.5
}
},
scales: {
y:
{
position: 'left',
},
},
};
public lineChartType: ChartType = 'line';
#ViewChild(BaseChartDirective) chart?: BaseChartDirective;
}
And here is the canvas used to display the chart and the result I got:
<canvas baseChart class="chart"
[data]="lineChartData"
[options]="lineChartOptions"
[type]="lineChartType"
(chartHover)="chartHovered($event)">
</canvas>
What's actually shown by my code
I suspect my tables of data implement the wrong type but I can't figure out why because they seem to be right.
I would really appreciate help with this problem because I really don't understand why it is not working.
I want to translate primeNG menu bar component. But I don't know how to handle the translation inside of .ts file. I want to get translate data from the .json file.
import { TranslateService } from '#ngx-translate/core';
import { SocialAuthService, SocialUser } from 'angularx-social-login';
import { MenuItem, MessageService } from 'primeng/api';
#Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.scss']
})
export class AdminComponent implements OnInit {
display: boolean = true;
socialUser: SocialUser = new SocialUser();
items: MenuItem[] = [];
constructor(private socialAuthService: SocialAuthService
, private toast: MessageService, private translateService: TranslateService
) {
this.items.map(item => item.label = this.translateService.instant(item.label));
}
ngOnInit(): void {
this.socialAuthService.authState.subscribe(_ => {
this.socialUser = _;
});
this.items = [
{ label: 'menu.pManagement', icon: 'pi pi-chart-line'},
{ label: 'menu.iList', icon: 'pi pi-wallet', routerLink: 'outsourcing' },
{ label: 'menu.iAnalysis, icon: 'pi pi-clock'}
];
}
addToast() {
this.toast.add({
severity: 'success',
summary: 'Success',
detail: ''
});
}
}
Upper you can see my menu bar items. I want to change the label name when I change the language from the language change dropdown.
here is the en.json file
{
"menu" : {
"pManagement" : "Project Management",
"iList" : "Item list",
"iAnalysis" : "Item analysis"
}
}
this treeview item text is confusing me for the past week
this is how I load the items into the tree view:
ngOnInit(): void {
this.items = this.getItems([JSON.stringify(this.json_obj)]);
}
getItems(parentChildObj: any[]) {
let itemsArray: TreeviewItem[] = [];
parentChildObj.forEach((set: TreeItem) => {
itemsArray.push(new TreeviewItem(set,true))
});
return itemsArray;
}
and this is how I create the nested Json object from non-nested Json file :
this.departments.forEach(element => {
if(element.ParentID == 0){
p_counter++;
this.json_obj.push(
{
text: element.DepartmentName ,
value: 'p'+p_counter.toString() ,
children: [],
id: element.DepartmentID.toString() ,
} as never
);
element.DepartmentName = 'fixed';
}
});
the template is simple as that:
<ngx-treeview [items]="items" dir ="rtl"></ngx-treeview>
btw- it creates a perfect nesting but it cant read the object properties in
new TreeviewItem(set,true);
because it's undefined.
Error : A text of item must be string object at new TreeviewItem
please help me figure this out, what can I do to make it work?
You have used
text: element.DepartmentName ,
value: 'p'+p_counter.toString() ,
children: [],
id: element.DepartmentID.toString()
It seems you have not followed TreeItem interface given in treeview-item.d.ts
export interface TreeItem {
text: string;
value: any;
disabled?: boolean;
checked?: boolean;
collapsed?: boolean;
children?: TreeItem[];
}
you should remove id because that is not property of TreeItem interface.
import { Component,OnInit } from '#angular/core';
import { TreeviewItem } from 'ngx-treeview';
#Component({
selector: 'my-app',
template: `<ngx-treeview [items]="items"></ngx-treeview>`
})
export class AppComponent implements OnInit {
items: TreeviewItem[];
ngOnInit() {
this.items = this.getItems();
}
getItems(){
// fetch api response
// convert response into this format (object can be nested, should contain below keys only with given type)
// {
// text: string;
// value: any;
// disabled ?: boolean;
// checked ?: boolean;
// collapsed ?: boolean;
// children ?: TreeItem[];
// }
const item = new TreeviewItem({
text: 'Children', value: 1, children: [
{ text: 'Baby 3-5', value: 11 },
{ text: 'Baby 6-8', value: 12 },
{ text: 'Baby 9-12', value: 13 }
]
});
return [ item ];
}
}
stackblitz example
My map is not loading and no error is being displayed in the console.
please help.
this is the error screenshot as shown in the browser
there is no build error while compiling the code neither any error is thrown but the ma form mabox is not loading and is written as - Missing mapbox Gl JS CSS
the following is the code snippet for the same
// code for map.component.ts
import { Component, OnInit } from '#angular/core';
import * as mapboxgl from 'mapbox-gl';
import { MapService } from '../map.service';
import { GeoJson, FeatureCollection } from '../map';
#Component({
selector: 'app-map-box',
templateUrl: './map-box.component.html',
styleUrls: ['./map-box.component.css']
})
export class MapBoxComponent implements OnInit{
/// default settings
map: mapboxgl.Map;
style = 'mapbox://styles/kanavmalik10/cjfbjx6fp70fl2snuphc7zjw2';
lat = 37.75;
lng = -122.41;
message = 'Hello World!';
// data
source: any;
markers: any;
constructor(private mapService: MapService) {
}
ngOnInit() {
this.markers = this.mapService.getMarkers()
this.initializeMap()
}
private initializeMap() {
/// locate the user
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
this.lat = position.coords.latitude;
this.lng = position.coords.longitude;
this.map.flyTo({
center: [this.lng, this.lat]
})
});
}
this.buildMap()
}
buildMap() {
this.map = new mapboxgl.Map({
container: 'map',
style: this.style,
zoom: 13,
center: [this.lng, this.lat]
});
/// Add map controls
this.map.addControl(new mapboxgl.NavigationControl());
//// Add Marker on Click
this.map.on('click', (event) => {
const coordinates = [event.lngLat.lng, event.lngLat.lat]
const newMarker = new GeoJson(coordinates, { message: this.message })
this.mapService.createMarker(newMarker)
})
/// Add realtime firebase data on map load
this.map.on('load', (event) => {
/// register source
this.map.addSource('firebase', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: []
}
});
/// get source
this.source = this.map.getSource('firebase')
/// subscribe to realtime database and set data source
this.markers.subscribe(markers => {
let data = new FeatureCollection(markers)
this.source.setData(data)
})
/// create map layers with realtime data
this.map.addLayer({
id: 'firebase',
source: 'firebase',
type: 'symbol',
layout: {
'text-field': '{message}',
'text-size': 24,
'text-transform': 'uppercase',
'icon-image': 'rocket-15',
'text-offset': [0, 1.5]
},
paint: {
'text-color': '#f16624',
'text-halo-color': '#fff',
'text-halo-width': 2
}
})
})
}
/// Helpers
removeMarker(marker) {
this.mapService.removeMarker(marker.$key)
}
flyTo(data: GeoJson) {
this.map.flyTo({
center: data.geometry.coordinates
})
}
}
<input type="text" [(ngModel)]="message" placeholder="your message...">
<h1>Markers</h1>
<div *ngFor="let marker of markers | async">
<button (click)="flyTo(marker)">{{ marker.properties.message }}</button>
<button (click)="removeMarker(marker)">Delete</button>
</div>
<div class="map" id="map"></div>
You seed to include the GL JS CSS stylesheet. See the quickstart at https://docs.mapbox.com/mapbox-gl-js/overview/#quickstart
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.45.0/mapbox-gl.css' rel='stylesheet' />
jsPDF allows to create a table form JSON data and save that table into a PDF document. I have created a Angualr2/Typescript application to do the same. This create table form my JSON data. I'm trying to use jsPDF is create a table with horizontal headers. Example for this given here. Code to create that is as follows.
// Horizontal - shows how tables can be drawn with horizontal headers
examples.horizontal = function () {
var doc = new jsPDF('p', 'pt');
doc.autoTable(getColumns().splice(1,4), getData(), {
drawHeaderRow: function() {
// Don't draw header row
return false;
},
columnStyles: {
first_name: {fillColor: [41, 128, 185], textColor: 255, fontStyle: 'bold'}
}
});
return doc;
};
Complete code is available here. This code is written in JavaScript. I'm looking for a way to convert this into Typescript. Does anyone have any idea how to do it?
Your component might look like this:
#Component({
selector: 'my-app',
template:
`<h1>JSON to PDF app</h1>
<div class="container" id="div1">
<button id="create" (click)="convert('base')">Create file</button>
<button id="create" (click)="convert('horizontal')">
Create file with horizontal table
</button>
</div>
`
})
export class AppComponent {
cols: Array<any> = [{
title: "Details",
dataKey: 'details'
}, {
title: "Values",
dataKey: 'values'
}];
optionsContainer = {
base: {},
horizontal: {
drawHeaderRow: () => false,
columnStyles: {
details: {fillColor: [41, 128, 185], textColor: 255, fontStyle: 'bold'}
}
}
};
rows: Array<any> = [];
constructor() {
const item = {
"Name" : "XYZ",
"Age" : "22",
"Gender" : "Male"
};
this.rows = Object.keys(item).map((key) => {
return { 'details': key, 'values': item[key] };
});
}
convert(action){
const doc = new jsPDF()
.autoTable(this.cols, this.rows, this.optionsContainer[action]);
doc.save('Test.pdf');
}
}
Demo Plunker