ngx-echarts icon indicating copy to clipboard operation
ngx-echarts copied to clipboard

dispatchAction not updating chart if echart directive is used in ng-template

Open slagbat opened this issue 1 year ago • 0 comments

I am using Angular and ngx-echarts v16.

I have a chart component library that uses ngx-echarts and it works great. I can put the directive in a reusable ng-template and the chart displays correctly and the initChart function is called, where I assign the chart to a variable in the component:

  initChart(event: ECharts): void {
    console.log("initChart");
    this.chart = event;
  }
<div class="dashboard-card">
  <ng-container *ngTemplateOutlet="headerTemplateRef || defaultHeaderTemplate"></ng-container>
  <ng-container *ngTemplateOutlet="contentTemplate"></ng-container>
</div>

<cpx-maximised [(visible)]="fullscreen" [header]="header" *ngIf="maximisable">
  <ng-container *ngTemplateOutlet="contentTemplate"></ng-container>
</cpx-maximised>

<ng-template #contentTemplate>
  <div class="content-row">
    <div class="legend" *ngIf="showLegend">
      <div class="legend-item" (click)="toggleSelected(c.name)" *ngFor="let c of legendItems"
        [ngClass]="{'unselected': !c.enabled}">
        <div class="circle" [ngStyle]="{'background': !c.enabled ? 'rgba(0, 0, 0, 0.1)' :  c.rgbColour}">
        </div>{{c.name}}
      </div>
    </div>
    <div class="chart-container">
      <div echarts [autoResize]="true" [options]="defaultOptions" [merge]="updatedChartOptions" class="chart"
        (chartInit)="initChart($event)">
      </div>
    </div>
  </div>
</ng-template>

In the above example I have a simple custom legend that calls a function that dispatches an action to toggle the legend item as such:

  toggleSelected(seriesName: string): void {
    this.chart.dispatchAction({
      type: "legendToggleSelect",
      name: seriesName,
    });

    const legendItemIndex = this.legendItems.findIndex(
      (x) => x.name === seriesName
    );
    this.legendItems[legendItemIndex].enabled =
      !this.legendItems[legendItemIndex].enabled;
  }

However, nothing happens when the action is dispatched, I assume because it can't find the chart object!

If I refactor the above view so that the chart is not in a template everything works perfectly albeit I have to manage 2 chart instances, which isn't the end of the world but I feel like I might be missing something obvious.

n.b. if I use the standard legend everything works fine but that doesn't work for me really and also the above is just an example of one particular action being dispatched.

slagbat avatar Dec 05 '23 00:12 slagbat