Search code examples
angularngx-charts

Angular NGX-Charts: using a custom legend


There was a previous question here, but I need clarification on the answer and don't have enough rep to comment. Paging user @Maya Sol.

I am trying to recreate her answer but I have not been successful and I am wondering where I am going wrong.

<ngx-charts-legend 
    [data]="sizeByTypeNames" 
    [title]="'Legend Title'" 
    [colors]="colors" 
    [activeEntries]="activeEntries" 
    (labelActivate)="legendLabelActivate($event)"
    (labelDeactivate)="legendLabelDeactivate($event)">
</ngx-charts-legend>



this.colors = new ColorHelper(this.colorScheme, 'ordinal', this.sizeByTypeNames, this.colorScheme);

this.sizeByTypeNames: string[] = [an array of the names each legend label should have]

I don't get any errors and I can see the legend title, but there is no content within the legend.


Solution

  • Component template and related functions:

    <div>
        <ngx-charts-pie-chart
            [scheme]="colorScheme"
            [results]="chart.data"
            (select)="onSelect($event)">
        </ngx-charts-pie-chart>
    </div>
    <div *ngIf="legend" class="chart-legend">
        <ngx-charts-legend 
            [data]="chart.legendData"
            [colors]="chart.colors"
            (labelClick)="onLabelClick($event, chart.data)">
        </ngx-charts-legend>
    </div>
    
    
    onLabelClick(event: any, data: any) {
        let result = data.find((obj: any) => {
            return obj.extra.displayName === event;
        })
        this.onSelect(result);
    }
    
    
    onSelect(event: any) {
        console.log(event);
    }
    

    Example of my DataSource, where I am getting data from an API and then setting these chart properties:

    chart: Chart =
        {
            title: 'Some Title',
            subtitle: 'A descriptive subtitle',
            data: this.chartData,
            legendData: [],
            colors: new ColorHelper('cool', 'ordinal', [], null),
            type: 'pie'
        }
    
    chartData = [];
    
    this.myService.getChartData(body).subscribe(
        result => {
            let data = result.data;
            for (let d in data) {
                let name = d;
                let val = data[d];
                let newDataPoint: NewDataPoint = {
                    'name': name,
                    'value': val,
                    'extra': {
                        'displayName': name,
                        'displayValue': val
                    }
                }
                this.chartData.push(newDataPoint);
            }
            chart.data = [...this.chartData];
            chart.legendData = chart.data.map(d => d['extra']['displayName']);
            chart.colors = new ColorHelper('neons', 'ordinal', chart.legendData, null);
        }
    );