Unselecting a line will result in the disabling of all chart lines

Currently, I am working with Primeng and incorporating multiple charts into my view. One feature of Primeng that I have successfully implemented is disabling lines. I am following this particular example:

Primeng provides a handy function on their site:

   selectData(event) {
        this.msgs = [];
        this.msgs.push({severity: 'info', summary: 'Data Selected','detail': this.data.datasets[event.element._datasetIndex].data[event.element._index]});
    }

To scale up the charts using *ngFor in Angular:

<div class="container">
  <div class="chart"  *ngFor="let chartVal of data">
  <app-chart [optionsIncome]="options" *ngIf="show"></app-chart>
  </div>
</div>

Although this function disables the line for one chart, my goal is to disable it across all other charts as well. Referencing the image below:

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

If I click on the First Dataset, I want the lines of other charts to be disabled. Is there a way to achieve this?

My start.compoment.hmtl

<input [(ngModel)]="inputValue" (ngModelChange)="reload()"/>
<select  (change)="selectedItem($event)">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>

  <div class="container">
      <div class="chart" *ngFor="let chartVal of data;let i = index">
        <app-chart #chart (click)="selectChart(i)" [optionsIncome]="options" *ngIf="show"></app-chart>
      </div>
    </div>

My start.component.ts looks like:

    import { Component, OnInit, ViewChildren } from '@angular/core';
    import {StartModel} from './start.model';
   @Component({
      selector: 'app-start',
      templateUrl: './start.component.html',
      styleUrls: ['./start.component.css']
    })
    export class StartComponent implements OnInit {

      public data = [];
      show = true;
      options: any;
      constructor() {
        this.options = {
          scales: {
              yAxes: [{
                  ticks: {
                      min: 0,
                      max: 20
                  }
              }]
          }
      };
      }

      ngOnInit() {

      }
      selectedItem(data) {

        if (data) {
          this.data.push(data);
          this.reload();
        }
        const minMax = {min: Math.random() * -1, max: Math.random() * 1};
        console.log(minMax.min, minMax.max)
        this.options.scales.yAxes[0].ticks.min = minMax.min;
        this.options.scales.yAxes[0].ticks.max = minMax.max;

      }

      reload () {
        this.show = false;
        setTimeout(() => this.show = true);
      }

    }

chart.component.html

<p-chart class="chart" type="line" [data]="data"  [options]="options"></p-chart>

chart.component.ts looks like this:

import { Component, OnInit, Input, ViewChildren } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnInit {

  data: any;
  msgs: any[];
  options: any;
  private _data = new BehaviorSubject({});
  selectChartIndex = 0;


  @Input() set optionsIncome(value) {
      this._data.next(value);
        }
  get optionsIncome() {
    return this._data.value;
  }
  constructor() {

    this.data = null;
    this.options = {};
  }
  ngOnInit() {
    this.data =  {
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
       datasets: [
        {
            label: 'First Dataset',
            data: [0.01, 0.25, 0.26, 0.4, 0.4, 0.37, 0.25],
            fill: false,
            borderColor: '#4bc0c0'
        },
        {
          label: 'Second Dataset',
          data: [0.11, 0.15, 0.26, 0.2, 0.4, 0.27, 0.1],
          fill: false,
          borderColor: '#4bc0c0'
      }
    ],
  };

  this.options = Object.assign({}, this.optionsIncome)

}

selectData(event) {
  console.log(event.optionsIncome)

}


}

Answer №1

Unable to access your data settings, so I am currently saving the index through a click event. However, a more efficient method would be to save the data and retrieve the index using event.options within the selectData() function. Here is the updated list:

  • Utilize viewChildren to retrieve all chart components
  • Access the chart instance and update the options using a for loop (if there is a wrapper for p-chart, ensure to obtain the chart instance through your app-chart)

For additional lifecycle hooks, refer to PrimeNG's source code or Chart.js documentation.

export class yourComponent {

  @ViewChildren('chart')
  chartCompoents: QueryList<any>;
  
  this.selectChartIndex = 0;

  selectChart(index){
     this.selectChartIndex = index;
  }

  selectData(event) {
    ...
    const isFirstChart = this.selectChart === 0;
    if(isFirstChart){
       chartCompoents.forEach(chartCompoent => {
          chartCompoent.chart.hide = true;
          chartCompoent.chart.update();
       });
    }
  }

}
<div class="container">
  <div class="chart" *ngFor="let chartVal of data;let i = index">
    <app-chart #chart (click)="selectChart(i)" [optionsIncome]="options" *ngIf="show"></app-chart>
  </div>
</div>

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 <mat-radio-button> component does not have a value accessor specified

When working with HTML and Angular, I encountered the following issue: <mat-radio-group> <mat-radio-button [(ngModel)]="searchType"> And (Narrower search) </mat-radio-button> <mat-radio-button [(ngModel)]="searchType"&g ...

Can ngFor be utilized within select elements in Angular?

I'm facing an interesting challenge where I need to display multiple select tags with multiple options each, resulting in a data structure that consists of an array of arrays of objects. <div class="form-group row" *ngIf="myData"> <selec ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

Having conflicting useEffects?

I often encounter this problem. When I chain useEffects to trigger after state changes, some of the useEffects in the chain have overlapping dependencies that cause them both to be triggered simultaneously instead of sequentially following a state change. ...

Utilizing a variety of Angular modules within Asp.Net Core

What is the optimal way to utilize multiple Angular 4 modules within the context of Asp.Net Core MVC? I am working on an application with various sections, each managed by a controller and view. Within these sections, I aim to incorporate sub-sections usi ...

The most suitable TypeScript type for a screen being utilized again in react-navigation v5

When it comes to typing screens under react-navigation v5, I usually follow a simple pattern: // Params definition type RouteParamsList = { Screen1: { paramA: number } Screen2: undefined } // Screen1 type Props = StackScreenProps<R ...

Error: React is throwing a SyntaxError because a ")" is missing in the argument list

While working on a React-typescript project using Vite, I encountered an issue where my page was displaying blank and showing the error : Uncaught SyntaxError: missing ) after argument list (at main.tsx:6:51) This error was found in the main.tsx file : im ...

Playing around with TypeScript + lambda expressions + lambda tiers (AWS)

Having trouble importing modules for jest tests in a setup involving lambdas, lambda layers, and tests. Here is the file structure: backend/ ├─ jest.config.js ├─ package.json ├─ babel.config.js ├─ layers/ │ ├─ tsconfig.json │ ├ ...

Tips on Calculating the Number of Object Properties and Presenting Each Value Individually on a Dynamic Button with Click Event Attached

When it comes to displaying dynamic data with markers on a map, everything works fine up until this point. However, I've encountered some issues that I'm currently stuck on and not sure how to proceed. Dynamic data: { "page": 2, "data" ...

Ways to create a versatile function for generating TypedArrays instances

I'm working on a function that looks like this: export function createTypedArray<T extends TypedArray>( arg : { source : T, arraySize : number } ) : T { if( arg.source instanceof Int32Array ) { return new Int32Array( arg.arraySize ); } ...

Exploring the intricacies of extracting nested JSON data in TypeScript

Can someone help me with this issue? https://example.com/2KFsR.png When I try to access addons, I only see [] but the web console indicates that addons are present. This is my JSON structure: https://example.com/5NGeD.png I attempted to use this code: ...

Why does Material-UI's "withStyles()" not function properly with a specified constructor in Typescript?

Update: Please note that there was an issue with the constructor generated by IntelliJ IDEA, but it has been fixed. You can find more details here: I'm exploring the use of Material-UI in my application, and I've encountered some challenges wit ...

Error message: Duplicate identifier found in Typescript

Encountering an error while trying to run my angular-meteor client (ionic serve), specifically: [00:29:20] typescript: node_modules/meteor-typings/1.3/main.d.ts, line: 657 Duplicate identifier 'Status'. L657: type Status ...

File handling in Angular 2 using Typescript involves understanding the fundamental syntax for managing files

Would someone be able to explain the fundamental syntax for reading and writing text files, also known as file handling in TypeScript? If there is a corresponding link that anyone could provide, it would be greatly appreciated. ...

Encountering issues with material 2 autoComplete onSelect() function after transitioning to Angular4

I recently made the transition to Angular 4 and material 2, but I'm encountering an issue with the autoComplete's onSelect() on md-option. It seems to be not working anymore and I can't seem to find any relevant documentation. Has anyone els ...

The data type 'boolean' cannot be assigned to the type 'StoryFnReactReturnType' in a React Storybook project using Typescript

I am currently working on setting up a Button component with Storybook in typescript. I am referencing The Documentation and using this specific example. Below is my Component and its story: components/Button.tsx: import {FC} from 'react'; exp ...

Enhance your Primeng split button with an added icon when selected

Is it possible to add a tick icon when the user selects the click option in a split button? Any advice on how to achieve this would be appreciated. Thank you. For example, similar to the image below: https://i.stack.imgur.com/owOgE.png ...

Assessing asynchronous HTTP function with Jamine: Exceeding time limit - No response received within 5000ms

ISSUE: Dealing with asynchronous functions returning Promises that rely on nested HTTP calls. USED TECHNOLOGIES: Angular 9, Jasmine 3.4.0 ERROR ENCOUNTERED: Error: Timeout - Async callback was not invoked within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INT ...

Issue with ngClass not updating during Route Event

I am using a bottomNavigation component that changes its style to indicate which route we are currently on. Below is the template for the bottom-navigation: class="menu-icon" [ngClass]="{ 'active-item': buttonActivated.value == '/my-goa ...

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...