首页 > 解决方案 > 如何在角度 6 中单击它时获取 highcharts 中图表的 Div id

问题描述

我在 angular6 中有一个简单的 highcharts 折线图。我需要获取图表的 onclick 所属图表的 div id。这里的 div id 是chart1,所以我需要在警报中获取它,还需要从图表外部调用。我已经尝试过,但它不工作,它显示空白。有什么解决方案吗。这是下面的代码。现场演示https://stackblitz.com/edit/angular-yw3xwa?file=src%2Fapp%2Fapp.component.ts

app.component.html

<hello name="{{ name }}"></hello>
<div (click)="onClickMe($event)" id="chart1"></div>

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import * as Highcharts from 'highcharts';
import * as Exporting from 'highcharts/modules/exporting';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  clickMessage = '';
  name = 'Angular';
  onClickMe(event) {
    alert(event.target.id);
  }
  ngOnInit(){
  this.chartFunc('chart1');
  }

  chartFunc(chartId){
  Highcharts.chart(chartId,{
   chart: {
         type: "spline"
      },
      title: {
         text: "Monthly Average Temperature"
      },

      series: [
         {
            name: 'Tokyo',
            data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2,26.5, 23.3, 18.3, 13.9, 9.6]
         }
      ]
   });
}
}

标签: javascriptangularhighcharts

解决方案


不需要传递整个事件(除非您需要事件的其他方面而不是您声明的)。事实上,不建议这样做。您只需稍作修改即可传递元素引用。

解决方案 1

html

<div #referenceKeyName (click)="onClickMe(referenceKeyName)" id="chart1"></div>

零件

onClickMe(referenceKeyName) {
  alert(referenceKeyName.id);
}

从技术上讲,您不需要找到被单击的按钮,因为您已经传递了实际元素。

解决方案 2

html

<div (click)="onClickMe($event)" id="chart1"></div>

零件

onClickMe(event: Event): void {
    let elementId: string = (event.target as Element).id;
    // do something with the id... 
}

推荐阅读