Strategies for selectively hiding datasets in Chart.js using Angular based on specified conditions

I successfully implemented a doughnut chart using the Chart.js plugin in Angular, as shown in the screenshot below.

https://i.sstatic.net/ADvOu.png

One problem I encountered is that when the dataset value drops below 100, it should automatically hide, like in the example below:

https://i.sstatic.net/ltsXw.png

If you'd like to view my complete code, feel free to check it out here.

I attempted to use a code snippet from this reference here, but unfortunately, it did not work as expected. The code I tried is:

pieChartData.data.forEach(function(ds) {
    ds.hidden = !ds.hidden;

If anyone could help me troubleshoot and resolve this issue, it would be greatly appreciated.

Answer №1

Try updating your ngOnInit function on StackBlitz and test if it meets your requirements

ngOnInit() {
    const self = this;
    this.pieChartData.forEach((value, index) => {
      if (value < 100) {
        self.pieChartData.splice(index, 1);
      }
    })
  }

Answer №2

If you are able to access the chart object through the wrapper, you can easily hide the dataset using the following method:

if (data < 100) {
  chartWrapper.getDatasetMeta(2).hidden = true
  chartWrapper.update()
}

I am not very familiar with the ng wrapper, so I cannot say for sure if they have exposed the chart object. If not, you may need to consider utilizing just the regular library and creating your own custom wrapper component.

Update: It seems that it is possible to access the chart object based on this discussion (ng2-charts access base chart object)

Answer №3

Setting up your data typically looks something like this:

this.barChartData = [
    { data: [1, 2, 3], label: 'legend'}
];

If you want to include an additional parameter called hidden:

this.barChartData = [
    { data: [1, 2, 3], label: 'legend', hidden: true }
];

Instead of hardcoding "true", it might be a good idea to run a test beforehand and store the result in a variable.

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

Issue: The code is throwing an error "TypeError: Cannot read property 'push' of undefined" in the JavaScript engine "Hermes

Can anyone assist me with filtering an array of objects in a TypeScript React Native project using state to store array values and filter objects in the array? Having trouble with the following error in the mentioned method: LOG after item LOG inside ...

Resolve the issue of text overflow in PrimeNG Turbo Table cells

When utilizing Primeng table and enabling the scrollable feature, the table is expected to display a scrollbar while ensuring that the text within the cells does not overflow. Unfortunately, this expected behavior is not occurring. To see an example of th ...

When attempting to compile the building project following the upgrade to Angular 9, an error message is displayed stating "Unable to access property 'length' as it is undefined

I'm currently in the process of updating my Angular 9 project by following the migration guide on update.angular.io. After running ng update @angular/core @angular/cli, I encountered an error "ERROR in Cannot read property 'length' of undefi ...

Angular: displaying dates in a specific format while disregarding time zones

Is there a way to format date-time in Angular using DatePipe.format() without converting timezones, regardless of location? For instance, for various examples worldwide (ignoring time differences) I would like to obtain 07/06/2022: console.log('2022-0 ...

Customize YouTube iframe styles in Angular 4+ with TypeScript

Has anyone been successful in overriding the style of an embedded YouTube iframe using Angular 4+ with TypeScript? I've attempted to override a CSS class of the embed iframe, but have not had any luck. Here is the URL to YouTube's stylesheet: ...

Analyzing the 'inactive' attribute of mat-checkbox

I am facing difficulty in changing the disabled property of mat-checkbox - https://material.angular.io/components/checkbox/api <mat-checkbox (change)="itemChanged()" [(ngModel)]="item.selected" [disableAfterClick]=" ...

Tips for simplifying union types in typescript without resorting to strings

One of my local state variables is defined as: const [select, setSelect] = useState<'' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h'>(''); I fi ...

Angular: Utilizing property interpolation from fetched JSON

As I attempt to create a test questionnaire using a json response, I encounter errors in the console stating 'Cannot read property 'Title' of undefined'. It seems like the string interpolation is trying to occur before receiving the res ...

Error encountered: Dev server does not have an interface defined

I recently utilized the react-ts template to create a project with vite v5. However, when I run the application using pnpm dev, an error message pops up: App.tsx:9 Uncaught ReferenceError: CharacterConnectionStatus is not defined at App.tsx:9:22 Look ...

Formatting numbers within the ngModel directive

How can I properly format a number using ngModel? When I attempted to do it like this <input type="number" [(ngModel)]="name.name.price | number:'1.2-3'">, it resulted in an error. What steps should I take to fix this is ...

Angular 6 is throwing an error stating that the 'publish' property is not found on the type Observable<string>

Currently, I am working on my initial Angular project using Angular 6. To streamline the process of handling errors in one central location, I have decided to incorporate Error Handling by referencing this insightful article on Medium From the code snipp ...

Creating a conditional property in TypeScript based on an existing type - a comprehensive guide

Imagine if I had the following: type Link = { text: string; link: string; } interface BigLink extends Link { some: number; something: string; else: string; } However, there's a variable that shares all these properties except for the fact ...

TypeScript functions with Generic Constraints return specific values rather than just types

function createGenericCoordinates<Type extends number | string>( x: Type, y: Type ) { return { x, y }; } const genericCoordinates = createGenericCoordinates(1, 2); // Error (TS2322) // Type 3 is not assignable to type 1 | 2 genericCoordinates ...

Customize nestjs/crud response

For this particular project, I am utilizing the Nest framework along with the nestjs/crud library. Unfortunately, I have encountered an issue where I am unable to override the createOneBase function in order to return a personalized response for a person e ...

The issue with type checking being disrupted when importing from a TypeScript file

I have a TypeScript file containing an openapi object schema constant: export default { "title": "Draft", "description": "A new draft listing", "type": "object", "additionalProperties ...

The ag-grid-n2 is giving me trouble with resolving all parameters for my editor component

In my Angular 2 project, I am setting up some editorFrameWork components for the ag-grid. However, I am encountering an issue when trying to inject services into the constructor of my editor component. The TypeScript compiler throws an error message when t ...

Exploring the differences between DDB.query and Raw Operation Object in CDK within AWS AppSync Resolver

Currently, I am in the midst of an AWS AppSync project utilizing CDK (Cloud Development Kit) to define my resolvers. While working on this project, I have stumbled upon two distinct approaches for writing DynamoDB query operations within my resolver functi ...

Is it possible for form controls to inherit from another form?

Two key elements make up my structure: The ParentComponent and ChildComponent: parent.component.ts <form #form="ngForm" (ngSubmit)="onSubmit(form)" novalidate> <input type="text" name="firstControl" [(ngModel)]="firstControl" /> ...

ng serve: Module 'tapable' not found

After moving my Angular 5 project to a new computer, I encountered an issue when attempting to ng serve: Cannot find module 'tapable' Error: Cannot find module 'tapable' at Function.Module._resolveFilename (module.js:469:15) at ...

Guide to utilizing the pdfjs worker in a React and TypeScript environment

I'm currently integrating pdfjs into a React and TypeScript project. import React from "react"; import * as pdfjs from "pdfjs-dist" export default function EditPdf() { React.useEffect(()=>{ const doc = pdfjs.getDocume ...