How to set Highcharts options in Angular 5 - highcharts

I tried to set following
Highcharts.setOptions({ lang: { thousandsSep: ',' } });
Trying to set thousand separator as default is space.
Error TS2686: 'Highcharts' refers to a UMD global, but the current
file is a module. Consider adding an import instead.
I am using "highcharts": "^6.1.0".
import {Component, OnInit, ViewEncapsulation,Inject, ViewChild,ElementRef,AfterContentInit, OnDestroy, Input} from '#angular/core';
import { chart } from 'highcharts';
import { Race } from '../../../race';
import { BaseComponent } from '../../../base/base.component';
#Component({
selector: 'nc-mobility',
templateUrl: './mobility.component.html',
styleUrls: ['./mobility.component.css']
})
export class MobilityComponent extends BaseComponent implements OnInit, AfterContentInit, OnDestroy {
#Input() mobility: Array<any>;
// highchart declarations
#ViewChild('mobilityDist') chartTarget: ElementRef;
chart: Highcharts.ChartObject;
constructor() { super(); }
ngOnInit() {
}
ngAfterContentInit() {
const options: Highcharts.Options = {
chart: {
type: 'column'
},
series: this.mobility.map(x => {
return { name: x.name, data: [x.value] };
}),
credits: {
enabled: false
}
};
this.chart = chart(this.chartTarget.nativeElement, options);
}
ngOnDestroy() {
this.chart = null;
}
}

Error occurs because you import only one function from Highcharts, by this:
import { chart } from 'highcharts';
In order to use setOptions, you need to also import this function or import whole Highcharts module, just like that:
import * as Highcharts from 'highcharts';

// import Highcharts
import Highcharts from "highcharts";
//set the options in your constructor
Highcharts.setOptions({
lang: {
thousandsSep: ","
}
});

Related

Having issues getting #ContentChild working with Directive

I've been trying to get ContentChild with Directive working in a demo/example and I keep running into the directive not working. No errors being thrown. I've replicated the scenario on StackBlitz and I'm getting the same problem: https://stackblitz.com/edit/angular-contentchild-directive-etktcd
Why am I still getting "undefined" for the child input?
Here is the Directive:
import { Component, Directive, Input, ContentChild, OnInit, OnDestroy, forwardRef, AfterContentInit} from '#angular/core';
import { AbstractControl } from '#angular/forms';
import { FocusDirective } from '../directive/focus.directive';
#Component({
selector: 'field-validation',
template: `
<ng-content></ng-content>
`
})
export class FieldValidationComponent implements OnInit, AfterContentInit {
#ContentChild(FocusDirective) input: FocusDirective;
ngOnInit(): void {
console.log("ngOnInit::input is: ", this.input);
// this.input.focusChange.subscribe((focus) => {
// this.updateAttributes();
// });
}
ngAfterContentInit(): void {
console.log("ngAfterContentInit::input is: ", this.input);
}
}
Here is the child Component:
import { Component, Directive, Input, ContentChild, OnInit, OnDestroy,
forwardRef, AfterContentInit} from '#angular/core';
import { AbstractControl } from '#angular/forms';
import { FocusDirective } from '../directive/focus.directive';
#Component({
selector: 'field-validation',
template: `
<ng-content></ng-content>
`
})
export class FieldValidationComponent implements OnInit, AfterContentInit {
#ContentChild(FocusDirective) input: FocusDirective;
ngOnInit(): void {
console.log("ngOnInit::input is: ", this.input);
// this.input.focusChange.subscribe((focus) => {
// this.updateAttributes();
// });
}
ngAfterContentInit(): void {
console.log("ngAfterContentInit::input is: ", this.input);
}
}
Here is the HTML in the parent app:
<form [formGroup]="testForm">
<field-validation>
<input type="text" placeholder="0.00">
</field-validation>
<div>
<button type="submit">FAKE SUBMIT</button>
</div>
</form>
Please add the FocusDirective class to declaration property of AppModule, as shown below.
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { FieldValidationComponent } from './child-component/field-validation.component';
import { RxReactiveFormsModule } from '#rxweb/reactive-form-validators'
import { FocusDirective } from './directive/focus.directive';
#NgModule({
imports: [ BrowserModule, ReactiveFormsModule, RxReactiveFormsModule],
declarations: [ AppComponent, HelloComponent, FieldValidationComponent, FocusDirective],
bootstrap: [ AppComponent ]
})
export class AppModule { }

How to use add series and update methods in the high chart wrapper for angular?

I am using high chart wrapper in my angular5 app with the help of below link.
high chart wrapper
but how can I use addSeries() to add series into the existing chart and how can I update the properties of existing chart.
how can I use addSeries() to add series into the existing chart and
how can I update the properties of existing chart.
When using highcharts-angular wrapper it is not recommended to use chart methods like addSeries() or update() directly on chart reference.
You have to update a whole component, not only chart properties. It can be achieved by updating chartOptions object (add new series, point, title etc) and setting updateFlag = true. Check the code and demo posted below.
app.module.ts:
import { BrowserModule } from "#angular/platform-browser";
import { NgModule } from "#angular/core";
import { HighchartsChartModule } from "highcharts-angular";
import { ChartComponent } from "./chart.component";
import { AppComponent } from "./app.component";
#NgModule({
declarations: [AppComponent, ChartComponent],
imports: [BrowserModule, HighchartsChartModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
chart.component.html:
<div class="boxChart__container">
<div>
<highcharts-chart
id="container"
[Highcharts]="Highcharts"
[constructorType]="chartConstructor"
[options]="chartOptions"
[callbackFunction]="chartCallback"
[(update)]="updateFlag"
[oneToOne]="true"
style="width: 100%; height: 400px; display: block;"
>
</highcharts-chart>
<button (click)="updateChart()">Update Chart</button>
</div>
</div>
chart.component.ts:
import { Component, OnInit } from "#angular/core";
import * as Highcharts from "highcharts";
import * as HighchartsMore from "highcharts/highcharts-more";
import * as HighchartsExporting from "highcharts/modules/exporting";
HighchartsMore(Highcharts);
HighchartsExporting(Highcharts);
#Component({
selector: "app-chart",
templateUrl: "./chart.component.html"
})
export class ChartComponent implements OnInit {
title = "app";
chart;
updateFlag = false;
Highcharts = Highcharts;
chartConstructor = "chart";
chartCallback;
chartOptions = {
series: [
{
data: [1, 2, 3, 6, 9]
}
],
exporting: {
enabled: true
},
yAxis: {
allowDecimals: false,
title: {
text: "Data"
}
}
};
constructor() {
const self = this;
this.chartCallback = chart => {
// saving chart reference
self.chart = chart;
};
}
ngOnInit() {}
updateChart() {
const self = this,
chart = this.chart;
chart.showLoading();
setTimeout(() => {
chart.hideLoading();
self.chartOptions.series = [
{
data: [10, 25, 15]
},
{
data: [12, 15, 10]
}
];
self.chartOptions.title = {
text: "Updated title!"
};
self.updateFlag = true;
}, 2000);
}
}
Demo:
https://codesandbox.io/s/oomo7424pz
Docs reference:
updateFlag - https://github.com/highcharts/highcharts-angular#options-details
here is a very useful answer for learning how to updata a highchart.
https://www.highcharts.com/demo/chart-update
it explains a method chart.update
chart.update({
chart: {
inverted: false,
polar: false
},
subtitle: {
text: 'Plain'
}
});
For adding series the following method is used
chart.addSerie(serie,true);
flag 'true' here is equivalent to chart.redraw();
OR
var chart = new Highcharts.Chart(options);
chart.addSeries({
name: array.name,
data: array.value
});
If you are going to add several series you should set the redraw flag to false and then call redraw manually after as that will be much faster.
var chart = new Highcharts.Chart(options);
chart.addSeries({
name: 'Bill',
data: [1,2,4,6]
}, false);
chart.addSeries({
name: 'John',
data: [4,6,4,6]
}, false);
chart.redraw();
For more information and methods you can visit the Official Highcharts API page:
https://api.highcharts.com/class-reference/Highcharts.Chart
When using angular-highcharts wrapper as
import { Chart } from 'angular-highcharts';
create charts as below
chart = new Chart({
chart: {
type: 'line'
},
title: {
text: 'Linechart'
},
credits: {
enabled: false
},
series: [
{
name: 'Line 1',
data: [1, 2, 3]
}
]
});
now you can call all API methods on this

React Native error the component must be a react component

So i am new to react native and JS in general, i have a huge background in native mobile development and i want to know more about Web Apps. So i try to begin with react native to experience that.
I wanted to do a side menu using createDrawerNavigator, so i created the following component :
// code for the menu
import React from 'react';
import { Platform } from 'react-native';
import { createStackNavigator, createDrawerNavigator, createAppContainer, DrawerActions } from "react-navigation";
import HomeScreen from '../screens/HomeScreen';
import LinksScreen from '../screens/LinksScreen';
import SettingsScreen from '../screens/SettingsScreen';
const App = createDrawerNavigator({
HomeScreen: {
screen: HomeScreen
},
LinksScreen: {
screen: LinksScreen
},
SettingsScreen: {
screen: SettingsScreen
}
},
{
drawerWidth: 300
});
export default createAppContainer(App);
// HomeScreen.js
import React from 'react';
import {
Image,
Platform,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
View,
Dimensions,
} from 'react-native';
import { WebBrowser } from 'expo';
import { DrawerNavigator } from 'react-native-navigation';
import { MonoText } from '../components/StyledText';
import { createStackNavigator, createDrawerNavigator, createAppContainer, DrawerActions } from "react-navigation";
import Router from './MenuNavigator';
export default class HomeScreen extends React.Component {
static navigationOptions = {
header: 'Vapeself 2',
};
render() {
const App = createDrawerNavigator({
Home: {
screen: MyHomeScreen,
},
Notifications: {
screen: MyNotificationsScreen,
},
});
const MyApp = createAppContainer(App);
this.props.navigation.dispatch(DrawerActions.openDrawer());
return (
<Router/>
);
}
// LinkScreen.js
import React from 'react';
import { ScrollView, StyleSheet } from 'react-native';
import { ExpoLinksView } from '#expo/samples';
export default class LinksScreen extends React.Component {
static navigationOptions = {
title: 'Links',
};
render() {
return (
<ScrollView style={styles.container}>
{/* Go ahead and delete ExpoLinksView and replace it with your
* content, we just wanted to provide you with some helpful links */}
<ExpoLinksView />
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 15,
backgroundColor: '#fff',
},
});
// SettingsScreen.js
import React from 'react';
import { ExpoConfigView } from '#expo/samples';
export default class SettingsScreen extends React.Component {
static navigationOptions = {
title: 'app.json',
};
render() {
/* Go ahead and delete ExpoConfigView and replace it with your
* content, we just wanted to give you a quick view of your config */
return <ExpoConfigView />;
}
}
I don't know what happened because the code doesn't work, and i have this kind of error The component for route 'HomeScreen' must be a React component . But the thing is that its actually work with a TabNavigator. So i really don't understand.
Thank you in advance for the help.

jquery-ui draggable cancel drag for parent

I have a console (div) absolutely positioned a top a leafletJS map. I have made it draggable using jquery-ui draggable plugin.
The problem is, when I drag the console the underlying map is also dragging. I am unsure as to which event on which element to stopImmediatePropagation on and when. Any ideas? I tried cancelling the click event on both start and stop handlers, but to no avail. (its wrapped as an Angular2+ Directive).
import {Directive, ElementRef, EventEmitter, Input, OnInit, Output} from '#angular/core';
declare var $: any;
#Directive({
selector: '[skinDraggable]'
})
export class DraggableDirective implements OnInit {
#Input('containmentSelector') containmentSelector: string;
constructor(private el: ElementRef) {}
ngOnInit() {
var me = this;
/** legacy since its available and ng has no decent equivalent */
$( this.el.nativeElement )
.draggable({
containment: this.containmentSelector,
scroll: false,
start: (event, ui) => {
// event.toElement is the element that was responsible
// for triggering this event. The handle, in case of a draggable.
$( event.originalEvent.target ).one('click', function(e){ e.stopImmediatePropagation(); } );
}
});
this.el.nativeElement.style.cursor = "move";
}
}
Made it, by disabling leaflet dragging on mousedown and then reenabling it on mouseup. The code shows some ngrx/store, but effectively leafletMap.dragging.enable() and disable() are being called, but only when the target is the overlay (not the map).
import {Directive, ElementRef, OnInit} from '#angular/core';
import {DraggableDirective} from "../../../widgets/draggable.directive";
import {Store} from "#ngrx/store";
import * as fromRoot from '../../../app.reducer';
import * as toolbarActions from '../../map-toolbar/map-toolbar.actions';
#Directive({
selector: '[skinPrintOverlayDraggable]'
})
export class PrintOverlayDraggableDirective extends DraggableDirective implements OnInit {
constructor(
el: ElementRef,
private store: Store<fromRoot.State>
) {
super(el);
}
ngOnInit()
{
super.ngOnInit();
//* preventing the map panning when the user drags the print overlay */
const mapContainer = document.querySelector('#map-container');
const map = document.querySelector('.mapboxgl-map');
mapContainer.addEventListener('mousedown', e => {
if (e.target === map) return true;
this.store.dispatch(new toolbarActions.SwitchDragPanActive(false));
});
mapContainer.addEventListener('mouseup', e => {
if (e.target === map) return true;
this.store.dispatch(new toolbarActions.SwitchDragPanActive(true));
});
}
}

Highcharts with angular2 and SystemJS Setup

had a tough time trying to get ng2-highcharts and angular2 to work nicely together.
what I have is;
import * as Highcharts from 'highcharts';
window['Highcharts'] = Highcharts;
bootstrap(AppComponent);
SystemJS Config;
map: {
"highcharts": "node_modules/highcharts/highcharts.js",
"ng2-highcharts": "node_modules/ng2-highcharts",
}
as you can see, this is quite a hack but its the only way I could get it working - when I remove the manual window assignment, I get
ReferenceError: Highcharts is not defined
at Ng2Highcharts.Object.defineProperty.set
So my question is, surely there is a better way? Any ideas?
I am using it like so;
import { Component, OnInit } from 'angular2/core';
import { Ng2Highcharts } from 'ng2-highcharts/ng2-highcharts';
#Component({
selector: 'component',
styleUrls: ['.comp.css'],
templateUrl: '.comp.html',
directives: [Ng2Highcharts]
})
Thanks
I have slightly modified the original implementation of ng2-highcharts I retreived few months ago to overcome some issues (I had to use jQuery - probably the most current version of the package does not need any twick any more). In any case this is the code of the directive I use
/// <reference path="../../typings/highcharts/highcharts.d.ts" />
declare var jQuery: any;
import {Directive, ElementRef, Input} from 'angular2/core';
#Directive({
selector: '[ng2-highcharts]'
})
export class Ng2Highcharts {
hostElement: ElementRef;
chart: HighchartsChartObject;
constructor(ele: ElementRef) {
this.hostElement = ele;
}
#Input('ng2-highcharts') set options(opt:HighchartsOptions) {
if(!opt) {
console.log('No valid options...');
console.log(opt);
return;
}
if(opt.series || opt.data) {
let nativeEl = this.hostElement.nativeElement;
let jQ = jQuery(nativeEl);
this.chart = jQ.highcharts(opt);
} else {
console.log('No valid options...');
console.dir(opt);
}
}
}
In index.html I have
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
},
ng2Highcharts: {
format: 'register',
defaultExtension: 'js'
},
.....
.....
}})
and
<script src="./lib/jquery/dist/jquery.js"></script>
<script src="./lib/highcharts/highstock.js"></script>
<script src="./lib/highcharts/modules/exporting.js"></script>
<script src="./lib/highcharts/highcharts-more.js"></script>
In the components that need to use the directive the html code looks like the following:
<div [ng2-highcharts]="chartOptions"></div>
chartOptions are created with code like this
createNewchartOptions() {
return {
title: {text: "Performance vs Benchmark (" + this.periodText + ")"},
rangeSelector: {
selected: 4},
xAxis: {
type: 'datetime'
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'}]
},
plotOptions: {
series: {
compare: 'percent'}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2}
};
}
Last thing you need to do is to set the series in the chartOptions (I do not put code since too linked to my app).
I hope this helps

Resources