import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, SimpleChanges, OnChanges } from '@angular/core'; import { trimLabel } from '../trim-label.helper'; import { formatLabel } from '../label.helper'; @Component({ selector: 'ngx-charts-advanced-legend', template: `
{{totalLabel}}
{{legendItem.label}}
`, changeDetection: ChangeDetectionStrategy.OnPush }) export class AdvancedLegendComponent implements OnChanges { @Input() width: number; @Input() data; @Input() colors; @Output() select: EventEmitter = new EventEmitter(); @Output() activate: EventEmitter = new EventEmitter(); @Output() deactivate: EventEmitter = new EventEmitter(); legendItems: any[] = []; totalLabel: string = 'total'; total: number; roundedTotal: number; ngOnChanges(changes: SimpleChanges): void { this.update(); } getTotal(): number { return this.data .map(d => d.value) .reduce((sum, d) => { return sum + d; }, 0); } update(): void { this.total = this.getTotal(); this.roundedTotal = this.total; this.legendItems = this.getLegendItems(); } getLegendItems(): any { return this.data.map((d, index) => { const label = formatLabel(d.name); const value = d.value; const percentage = value / this.total * 100; const color = this.colors.getColor(label); return { value, color, label: trimLabel(label, 20), originalLabel: d.name, percentage }; }); } trackBy(item) { return item.formattedLabel; } }