Guide on bringing highcharts-more into an Angular-CLI 6 project

Running into an issue in my angular-cli 6 project where I'm using highcharts to create a solid-gauge. The error message I received can be found here. To resolve this, I had to include the highcharts-more.js file in my component.

For highcharts, I have installed the following npm packages:

  • npm install highcharts
  • npm install --save-dev @types/highcharts (recommended by VS Code when trying to import highcharts)

Below is the code snippet for my component along with the necessary imports:

import {
  AfterViewInit,
  Component,
  ElementRef,
  Injector,
  OnInit,
  ViewChild
} from '@angular/core';
import * as Highcharts from 'highcharts';
import { chart } from 'highcharts';
import highchartsMore from 'highcharts/highcharts-more';
import { AbstractDashboardCard } from '../../models/abstract-dashboard-card';
import { DashboardCard } from '../../models/dashboard-card';

highchartsMore(Highcharts);
@Component({
  selector: 'app-luchtkwaliteit',
  templateUrl: './luchtkwaliteit.component.html',
  styleUrls: ['./luchtkwaliteit.component.css']
})
export class LuchtkwaliteitComponent extends AbstractDashboardCard
  implements OnInit, AfterViewInit {
  @ViewChild('chartTarget') chartTarget: ElementRef;
  chart: Highcharts.ChartObject;

  constructor(private injector: Injector) {
    super(
      injector.get(DashboardCard.metadata.NAME),
      injector.get(DashboardCard.metadata.SOURCE),
      injector.get(DashboardCard.metadata.COLS),
      injector.get(DashboardCard.metadata.ROWS)
    );
  }

  ngOnInit() {}

  ngAfterViewInit() {
    const gaugeOptions = {
      chart: {
        type: 'solidgauge'
      },
      title: null,
      pane: {
        center: ['50%', '85%'],
        size: '140%',
        startAngle: -90,
        endAngle: 90,
        background: {
          backgroundColor: '#EEE',
          innerRadius: '60%',
          outerRadius: '100%',
          shape: 'arc'
        }
      },
      tooltip: {
        enabled: false
      },
      // the value axis
      yAxis: {
        stops: [
          [0.1, '#55BF3B'], // green
          [0.5, '#DDDF0D'], // yellow
          [0.9, '#DF5353'] // red
        ],
        lineWidth: 0,
        minorTickInterval: null,
        tickAmount: 2,
        min: 0,
        max: 200,
        title: {
          y: -70,
          text: 'Speed'
        },
        labels: {
          y: 16
        }
      },
      plotOptions: {
        solidgauge: {
          dataLabels: {
            y: 5,
            borderWidth: 0,
            useHTML: true
          }
        }
      },
      credits: {
        enabled: false
      },
      series: [
        {
          name: 'Speed',
          data: [80],
          dataLabels: {
            format:
              '<div style="text-align:center"><span style="font-size:25px;color: black' +
              '">{y}</span><br/>' +
              '<span style="font-size:12px;color:silver">km/h</span></div>'
          },
          tooltip: {
            valueSuffix: ' km/h'
          }
        }
      ]
    };
    this.chart = chart(this.chartTarget.nativeElement, gaugeOptions);
  }
}

I've tried various ways to add highcharts-more but encountered roadblocks. Here's what I tried:

  • npm install highcharts-more (deprecated so avoided using it) Link
  • import * as highchartsMore from 'highcharts/highcharts-more'; Received TS error "node_modules/@types/highcharts/highcharts-more" resolves to a non-module entity and cannot be imported."
  • import * as highchartsMore from 'highcharts'; TS Error on highchartsMore(Highcharts); Cannot invoke an expression whose type lacks a call signature.
  • highcharts-angular (not used due to compatibility issues with angular 6) Link

Answer №1

To utilize the solid-gauge series type, you must first import the necessary module.

import * as Highcharts from 'highcharts'
import * as solidGauge from 'highcharts/modules/solid-gauge'

solidGauge(Highcharts)

Answer №2

Here is the method I use to import it into my Angular 5 project, and it appears to be functioning correctly.

require('highcharts/highcharts-more')(Highcharts);

Answer №3

Utilizing solidGauge in Angular 6, I encountered the need to eliminate all "requires" statements for HighCharts. After extensive experimentation, I successfully managed this for more intricate charts. The key is to append .src to the Imports causing import errors.
Here's a functional example:

Within the module:

import * as Highcharts from 'highcharts'; 
//*****  append .src to the following imports that won't import otherwise  ********
import * as more from 'highcharts/highcharts-more.src';  
import * as solidGauge from 'highcharts/modules/solid-gauge';  
import * as exporting from 'highcharts/modules/exporting.src';    
import * as exportdata from 'highcharts/modules/export-data.src';    
import * as offlineexporting from 'highcharts/modules/offline-exporting.src';     


more(Highcharts);  
solidGauge(Highcharts);  
exporting(Highcharts);    
exportdata(Highcharts);    
offlineexporting(Highcharts);     

Inside the component:

    import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core'; 
    import { chart } from 'highcharts';

    export class GaugeData {
      public width: number;
      constructor(  public title: string, public value: number, public color: string) { }
    }


    @Component({
        selector: 'radialgauge',
        template: `
            <div #chartTarget> </div>
        `
    })
    export class GaugeComponent {
        @ViewChild('chartTarget') chartTarget: ElementRef;
        @Input() data: GaugeData;  
        public thisdata: GaugeData;
        public options: Object;
        public chartwidth: number = 250;
        public chartheight: number = 200;
        public topmargin:number= 50;
        public center: string[] = ['50%', '50%'];
        chart1: Highcharts.ChartObject;

        constructor() {
            this.thisdata = new GaugeData('',0,'#000')
        };

        ngOnChanges() {
            this.thisdata = this.data;
            this.setOptions(this.thisdata);
            this.chart1 = chart(this.chartTarget.nativeElement, this.options);
        }

        ngOnInit() {
            this.thisdata = this.data;
            this.chartwidth = this.width;
            if (this.height) {
                this.chartheight = this.height;
            }
            if (!this.showtitle) {
                this.thisdata.title = '';
                this.topmargin = 0;
                this.center = ['30%', '55%'];
            }
            this.setOptions(this.thisdata);
            this.chart1 = chart(this.chartTarget.nativeElement, this.options);
        }

        setOptions(newData: GaugeData) {

            this.options = {
                chart: {
                    type: 'solidgauge',
                    marginTop: this.topmargin,
                    backgroundColor: "none",
                    height: this.chartheight,
                    width: this.chartwidth
                },
                credits: { enabled: false },
                exporting: {
                    enabled: false,
                    showTable: false
                },
                title: {
                    text: newData.title,
                    style: {
                        fontSize: '12px', color: "#fff", fontfamily: "Arial", width:"200px"
                    },
                },
                tooltip: { enabled: false },
                pane: {
                    startAngle: 0,
                    endAngle: 360,
                    background: [{ // Track for Move
                        outerRadius: '115%',
                        innerRadius: '0%',
                        backgroundColor: "rgba(74, 70, 66, 1)",
                        borderWidth: 0
                    }],
                    center: this.center,
                },
                yAxis: {
                    min: 0,
                    max: 100,
                    lineWidth: 0,
                    tickPositions: [],
                    color: "#fff",
                    title: {
                        text: '<span style="font-size:36px;color:white;font-family: \'Arial\'">' + newData.value + '%</span>',
                        x: 5,
                        y: 43
                    }
                },
                plotOptions: {
                    solidgauge: {
                        dataLabels: {
                            enabled: false
                        },
                        stickyTracking: false
                    }
                },
                series: [{
                    data: [{
                        color: newData.color,
                        radius: '115%',
                        innerRadius: '105%',
                        y: newData.value
                    }]
                }]
            }

        }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

the angular variable scope has not been defined

Currently, I am developing an angular controller that is configured to utilize the "controller as" syntax: angular.module('app', []).controller('ctrl1', ctrl1); ctrl1.$inject = ['$http', '$compile']; function ctrl ...

In testing environments, Template Updates do not occur

I have encountered a challenge while testing Angular code and it seems like there may be confusion surrounding template updates. Here's what I am attempting to achieve: I have created a component that consists of a search input which can be cleared by ...

Getting a comprehensive list of functions that can be used with a Class in Node.js

I'm on a quest to find a straightforward method to retrieve the list of functions available for a class in Node.js using the command line. After some online research, I came across Object.getOwnPropertyNames(), but it seems inconsistent as it works f ...

Trouble installing TypeScript on MacBook - Terminal Glitch

I recently got Visual Studio Code on my Mac and wanted to add TypeScript for Angular. I believe I already installed Node.js or Git in the past. However, when I tried running this command from the TypeScript website in the Mac Terminal to install TypeScript ...

Obtaining the HTML content of a div element that has been retrieved through an AJAX request to a PHP script

My challenge is to fetch a dropdown menu from a server and then manipulate it using jQuery after loading. Although everything loads correctly, I am unable to interact with the dropdown items because they were dynamically added post AJAX response instead of ...

Secure access to an API using a certificate within a Vue.js application running on localhost

My vue.js app is built using vue-cli. The application is hosted at dev.example.com and the REST API can be found at dev.example.com/api/v1/. The backend has added an SSL certificate for security on the development environment. However, when I try to make a ...

Can metadata be attached to data models in Angular for annotation purposes?

Looking to add some metadata annotations to a simple data model export class Certification { title: string; certificationType?: CertificationType; validTo?: number; description?: string; externalIdentifier: Guid; constructor() { ...

ReactJS Error: Unable to modify the read-only property 'cartHandler' of object '#<Object>' - TypeError

Currently, I'm in the process of creating a restaurant website. I have successfully completed half of it but seem to be facing some difficulties now. I encountered an error that I can't quite pinpoint in my code. Every time I attempt to add a new ...

NativeScript does not acknowledge the permission "android.Manifest.permission.READ_CONTACTS"

Hi there! I am a beginner in mobile development and currently learning Angular 2. I am facing an issue with requesting permission for reading contacts in NativeScript. It seems that "android" is not being recognized. For instance, when trying to execute t ...

What is the best way to merge append() and replaceWith() functions in jQuery?

Is there a way in Jquery to merge the functions of append() and replaceWith()? In my JQM project, I have a login form that appears on every page. Since multiple pages are loaded into the DOM, I need to shift the form along as the user navigates through th ...

Guide on streamlining interface initialization within a React project using Typescript

Working on my Typescript project, I consistently utilize an interface within the State of various components: interface Item { selectedValue: string originalSelectedValue: string loading: boolean disabled: boolean isValid?: boolean } ...

Unable to construct Vue application after integrating webpack extension

Currently facing an issue with adding a webpack extension to build my Vue app. Despite having Vue/cli which includes webpack, I have also attempted to install different versions of webpack without success. Anyone experienced the same problem and found a so ...

What is the importance of typescript requiring the use of generics?

const typeFunction = <T>(a:string, {c,d} = {c: T[], D:T} = {})=>{} In what way does TypeScript enforce the usage of generics? I am looking to create a function that requires a specific type (T) to be passed in when it is used. typeFunction<st ...

Identifying a broken lock icon caused by a mix of secure and insecure content using JavaScript

Currently, I am in the process of ensuring that our website is fully functional under HTTPS. One important aspect of this is to prevent any occurrence of "breaking the lock." It is crucial not to load non-SSL content on an SSL page as this can result in a ...

What is the reason behind ModelBinding not functioning with FormData but being compatible with RequestPayload?

Recently, while working with Web API, I came across an interesting observation that has left me puzzled. controller: $.ajax with additional configurations like type, contentType, accept, the model doesn't bind correctly, whereas it works fine with $ ...

Navigating through an array to extract necessary information within an Angular framework

Below is the JSON data I have: [{ "_id": 1, "Name": "x", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6dce6c3d6d5cfcac9c888c5c9cb">[email protected]</a> ", "Designation": "Manager", "Projec ...

"GM_openInTab in Userscript (Scriptish) not working properly, returning null value

There seems to be a problem with window.opener that I am facing. When I utilize window.open("url"), the child window will reference window.opener properly. However, if I use GM_openInTab instead, which is supposed to be the equivalent option for cross bro ...

IE8 is having trouble with JavaScript errors

I recently downloaded a tooltip from the following website: . It worked perfectly on all updated browsers except for Internet Explorer 8. In IE 8, only the first tooltip loads and the others do not display. Below is the code snippet that I used: <img ...

Ways to restart the random number generator in JavaScript

Just embarked on my first JavaScript project and I'm aiming to create a personalized slot machine. However, I've hit a roadblock - I can't figure out how to restart my program or the function for generating new random values repeatedly. Here ...

The Sequelize findOne method fails to return the desired results, resulting in an empty

My findOne function with include is not working as expected. It is not returning any data. I am missing data for Deal, which is related to Redemption [] <- I should have data here. Deal.belongsTo(models.Redemption, { foreignKey: 'redemptionI ...