score:0

Accepted answer

i went round and round trying a range of different implementations to solve this very problem for myself while using ng2-charts (incidentally it is how i found this question). i ended up adding an @viewchild to reference my chart that was defined in the html.

references needed in the ts for this workaround:

import { component, input, host, oninit, ondestroy, viewchild, afterviewinit } from '@angular/core';
import { chartsmodule, basechartdirective } from 'ng2-charts';

added to the top of my class in the ts:

export class statisticscomponent implements oninit, ondestroy {

  @viewchild('mychart') mychart : basechartdirective;

the html object for the chart using ng2-charts:

<canvas *ngif = "loaded" 
        basechart
        #mychart = 'base-chart'
        [datasets]="chartdata"
        [colors]="chartcolors"
        [charttype]="'line'"      
        [labels]="chartlabels"
        [options]="chartoptions"
        [legend]="true"
        (chartclick)="onchartclick($event)">
    </canvas>

in the method you then use for overriding the legend onclick (i personally did it in the chartoptions) you can add this line of code:

this.chart.data.datasets[legenditem.datasetindex].hidden = !this.chart.data.datasets[legenditem.datasetindex].hidden;
this.chart.update();

this replicates the standard "onclick" of the legend item so you dont need to bother storing the original function. probably important to mention that in this code the legenditem is the second parameter from the onclick (with the first being the event):

function(e: any, legenditem: any)

the only issue with this fix is that by default, in ng2-charts the .hidden artibute is not exposed by default so i had to do a little hack in the module following this method: https://github.com/valor-software/ng2-charts/issues/915.

while i appreciate your question does not relate to ng2-charts. i imagine that you could likely use a similar method in your wrapper. at the very least i figured that after i managed to sort my problem that i would share with you what i did :)


Related Query