Display a fixed three levels of highchart Sunburst upon each click in Angular8

Looking to create a dynamic sunburst highchart that displays three levels at a time while allowing interactive drilling. For instance, if there are 5 levels, the chart should initially show the first three levels. When clicking on level 3, levels 2, 3, and 4 should be displayed, and so on.

Below is the AngularV8 implementation:

.html file

<div class="kt-widget14__chart" style="min-height:300px;">
   <div class="chartjs-size-monitor-new">
       <highcharts-chart [Highcharts]="highcharts" [options]="company360SunburstOptions"
           style="width: 100%; height: 100%; display: block;">
       </highcharts-chart>
   </div>
</div>

.ts file


this.myService.getData().subscribe(result => {
            this.chartOptions.series[0].data = result;
            this.chartOptions.series[0].point = {
                events: {
                    click: (function (event) {
                        that.poinClicked(data);
                    })
                }
            };
        });

    chartOptions = {
        chart: {
            type: "sunburst",
            height: '100%',
        },
        credits: {
            enabled: false
        },
        exporting: { enabled: false },
        title: {
            text: ''
        },
        subtitle: {
            text: ''
        },
        plotOptions: {
            series: { // or general options: "series: { ... }"
                dataLabels: {
                    format: '{point.name}',
                    filter: {
                        property: 'innerArcLength',
                        operator: '>',
                        value: 16
                    },
                    enabled: true,
                    style: {
                        textShadow: false
                    }
                },
                animation: false
            }
        },
        series: [{
            type: "sunburst",
            data: [],
            allowDrillToNode: true,
            cursor: 'pointer',
            point: {},
            levels: [{
                level: 1,
                levelSize: {
                    units: 'percentage',
                },
                hidden: false,
                dataLabels: {
                    enabled: true
                }
            }, {
                level: 2,
                hidden: false,
                dataLabels: {
                    enabled: true
                }
            }, {
                level: 3,
                hidden: true,
                dataLabels: {
                    enabled: false
                },
                levelSize: {
                    value: 0
                }
            }, {
                level: 4,
                hidden: true,
                dataLabels: {
                    enabled: false
                },
                levelSize: {
                    value: 0
                }
            }]
        }],
        tooltip: {
            enabled: false
        }
    };

pointClicked() {

   let level = data['Level'];
   level = level + 1;
   if (level == 1) {
      this.sunburstShowLevels([1,2])
   } else if (level == 2) {
       this.sunburstShowLevels([1,2,3])
   } else if (level == 3) {
       this.sunburstShowLevels([2,3,4])
   }
}

sunburstShowLevels(levelIdList) {
   // Will get a list of levelIds that should be display
   let levels = this.chartOptions.series[0].levels; // Whole levels object
   let newLevels = [];
   for (var index=0; index<levels.length; index++) {
       var level = levels[index];
       if (levelIdList.includes(level['level'])) {
          // Then show it
          level.hidden = false; // set flag
          level['levelSize'] = {value: 1};
          level['dataLabels'] = {enabled: true}
       } else {
           level.hidden = true; // set flag
          level['levelSize'] = {value: 0};
          level['dataLabels'] = {enabled: false}
       }
       newLevels.push(level);
    }
}

Although the code works correctly in displaying the desired levels upon clicking, an issue arises where two clicks are required for the functionality to take effect. For example, when clicking on the second level, it initially shows only level 2 before displaying levels 1, 2, and 3 after the second click.

Challenge

In conclusion, the goal is to efficiently display specific levels upon each click without the need for multiple clicks to trigger the desired behavior. Seeking alternative suggestions or improvements to streamline this process. Grateful for any assistance.

Thank you in advance.

Answer №1

I came up with a new approach to achieve this by utilizing the series.update functionality for updating level options.

Check out the demo here: https://jsfiddle.net/BlackLabel/zrt4m13g/

Below is the code snippet:

point: {
  events: {
    click(e) {
      let series = this.series,
        clickedLevel = this.node.level,
        currentOptions = series.userOptions.levels;

      for (let i of currentOptions) {
        if (clickedLevel !== 0 /*or 1 */ && clickedLevel !== currentOptions.length) {
          if (i.level === clickedLevel || i.level === clickedLevel + 1 || i.level === clickedLevel - 1) {
            i.levelSize = {
              value: 1
            }
          } else {
            i.levelSize = {
              value: 0
            }
          }
          i.dataLabels = {
              rotationMode: 'parallel',
              filter: {
                property: 'outerArcLength',
                operator: '>',
                value: 64
              },
              enabled: true
          }
        }
      }

      series.update({
        levels: currentOptions
      })
    }
  }
},

For more information, refer to the API documentation: https://api.highcharts.com/highcharts/series.sunburst.levelSize

Explore the Series API update method here: https://api.highcharts.com/class-reference/Highcharts.Series#update

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

After an Ajax request, the functionality of Javascript/Jquery ceases to work

After successfully submitting a form via ajax for the first time, the subsequent submissions seem to break all javascript functionality on the page. Additionally, the form is unable to submit with ajax again. Below is the code snippet for the ajax call: ...

Error message in Typescript: When a class has initialized properties, a 'super' call must be the first statement in the constructor

I am currently facing some typescript errors in my project. Would you like to see a sample of the code that is causing the issue? Here is a snippet: module CoreWeb { export class Controller implements IController { public $q; ... This piece of cod ...

Using TypeScript's `async await` within a nested function invocation

I am having trouble extracting the 'assigned suspect' from the callbacks, as it is showing up as undefined. Strangely, it works fine within an if statement. I believe the issue is related to the await/async functionality. Any assistance would be ...

Having trouble with the babel-loader and its version compatibility, as well as not finding the babel-loader folder in the node_modules directory when

Here are the steps I've taken: I cloned the project from Github. Ran the command 'yarn' to start the project. Encountered an error after running the command 'yarn start'. Even after following the steps provided in the e ...

TS2304 error: 'Promise' is nowhere to be found

Hey everyone, I've exhausted all the solutions available on stackoverflow with no luck. So here's my question. tsconfig.json { "version":"2.13.0", "compilerOptions": { "target": "es5", "module": "commonjs", "sourceMap": true, ...

"Efficiently setting up individual select functions for each option in a UI select menu

I've integrated UI Selectmenu into my current project UI selectmenu includes a select option that allows for setting select behavior across all selectmenu options, as shown in the code snippet below: $('.anything'). selectmenu({ ...

What is the most effective method for transferring data to a concealed input field?

I currently have a webpage with dual forms - one on the main page and another within a Bootstrap modal. The primary form includes fields like "Neck, Chest, Waist," while the modal's form only has an email field. To streamline the submission process, ...

Solve the problem with SCSS at the component level in NextJS

I've decided to transition my regular React app to Next.js. In the past, I would simply import SCSS files using: import from '.componentName.scss' However, now I need to import them using: import style from 'componentName.module.scss ...

What steps can I take to resolve a dependency update causing issues in my code?

My program stopped working after updating one of the dependencies and kept throwing the same error. Usually, when I run 'ng serve' in my project everything works fine, but after updating Chartist, I encountered this error: An unhandled exception ...

Conceal the div class upon clicking it

I'm dealing with a list of videos and I need to hide the class when it's clicked. Check out this sample HTML output: <div id="primary-video"> <iframe id="video" width="100%" height="auto" src="https://www.youtube.com/embed/test" fra ...

How can we incorporate spans into child elements using JavaScript?

Recently, I encountered a problem with a code that is supposed to add a span if it doesn't already exist on certain elements. However, the current implementation only adds the span to one element and not others because the code detects that it already ...

"Enhancing User Interaction with AngularJS: Leveraging ng-click and ng

Currently, I have a map with markers that trigger an overlay-div to open when clicked. <div class="map" ng-init="loadall()"> <a ng-click="details.show=!details.show" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker ...

Intellisense for dispatch types in Redux Toolkit

After following the documentation for redux toolkit with typescript, I implemented my own useDispatch hook as shown below export const useAppDispatch = () => useDispatch<AppDispatch>() and used it in components like this const dispatch = useAppDi ...

In JavaScript, split each element in an array into individual elements

Is there a way to split elements separated by commas into an array in JavaScript? ["el1,el2", "el3"] => ["el1", "el2", "el3"] I am looking for a solution to achieve this. Can you help me with that? ...

Error TS2345: The function with arguments of type '(req: any, res: any, ctx: any) => any' cannot be assigned to the parameter of type 'HttpResponseResolver<PathParams<string>'

Encountered an issue in a React TypeScript test case involving mock data. The error message received was: TS2345: Argument of type '(req: any, res: any, ctx: any) => any' is not assignable to parameter of type 'HttpResponseResolver<P ...

When logging off from an Angular2 application, the OIDC-client does not properly clear the cookies for the MVC application

I currently have an authorization server that is being used by both my Angular2 app and MVC webapp. In my Angular2 app, I've implemented authorization using the oidc-client JavaScript package. Everything works well except for the logout functionality ...

Ways to eliminate the lower boundary of Input text

Currently, I am working on a project using Angular2 with Materialize. I have customized the style for the text input, but I am facing an issue where I can't remove the bottom line when the user selects the input field. You can view the red line in t ...

Troubleshooting issues with sending data from Node.js to MongoDB

I recently started learning nodeJS and I'm facing an issue with sending data from a register form to mongodb. It seems like I made a mistake while using the post method, as I am unable to see the data on postman. const express = require('express& ...

Retrieve the value of EJS depending on the JavaScript variable

I am in the process of developing a website for booking appointments using Express, EJS, and MongoDB. When a request is made to '/booking', the book page appears displaying all details about the doctor. Upon clicking the book button next to each ...

Is there a way to print messages to the console of openDevTools in Electron JS?

After finishing a hello world application using electron js, I have successfully printed to my terminal with console.log and opened the openDevTools in the window of my application. However, I am now interested in finding a way for my console.log stateme ...