SoFunction
Updated on 2025-04-13

Detailed explanation of the use of echarts map in angular

When using echart in angular, you only need to call the echart API in the corresponding component life cycle.

Initialization of echart

Initialize echarts in the ngOnInit event of component, configure option, and then the echarts chart is generated

app-base-chart component

html

<div #chart [ngClass]="'chart-box ' + (!option ? 'empty-chart' : '')"></div>

css

// Basic chart style.chart-box{
  font-weight: bold;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
}
// The style when option is not available.empty-chart{
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
}
import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { fromEvent, Subscription, timer } from 'rxjs';
import { debounceTime, tap } from 'rxjs/operators';
import { ECharts, EChartsOption, init } from 'echarts';
@Component({
  selector: 'app-base-chart',
  templateUrl: './',
  styleUrls: ['./']
})
export class BaseChartComponent implements OnInit, OnDestroy {
  @Input() option: EChartsOption;
  @Input() height = '300px';
  @Input() width = '100%';
  @ViewChild('chart', { static: true }) chart: ElementRef;
  aChart: ECharts;
  windowResize: Subscription;
  timer: Subscription;
  defaultGrid = {
    top: 10,
    right: 10,
    bottom: 30,
    left: 30,
  };
  constructor() { }
  ngOnInit(): void {
    ();
    ();
    if (!!) {
      ();
    }else{
       = 'No data yet';
    }
  }
  // When component is destroyed, cancel the relevant subscription  ngOnDestroy(): void {
    if () {
      ();
    }
    if () {
      ();
    }
  }
  // Initialize the size of the container  boxStyleInit(): void {
     = ;
     = ;
  }
  // Set the window's resize event listening and redraw the size of echarts  setListen(): void {
     = fromEvent(window, 'resize').pipe(
      debounceTime(200),
      tap(res =&gt; {
        ();
      })
    ).subscribe();
  }
  // Configure and generate echarts charts according to option  echartsInit(): void {
     = init();
    (({ grid:  }, ));
    //Re-draw echarts size through delay     = timer(400).subscribe(res =&gt; {
      ();
    });
  }
}

Use the app-base-chart component

<app-base-chart [option]="option" width="100%" height="300px" ></app-base-chart>

You only need to use the above code in the component's html, and you can also configure height and width. option is the option officially defined by echarts

This actually simply encapsulates a basic echarts generation component, and all configuration items are echarts

Summarize

That’s all for this article. I hope it can help you and I hope you can pay more attention to more of my content!