我正在使用启用了工具提示功能的ng2折线图。图表加载完成后,我想以编程方式在最新点上显示工具提示。
我环顾四周,找到了一些解决方案,这些解决方案通过捕获要避开的兴趣点的位置来手动创建悬停事件。我也在寻找一种更好的方法,但是找不到。
下面是我的代码和配置数据。解决问题的任何其他方法都将有所帮助。
import { Component, OnInit, ViewChild} from '@angular/core';
import { ChartDataSets} from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
import 'hammerjs';
import * as zoomPlugin from 'chartjs-plugin-zoom';
import { OnChanges } from '@angular/core';
@Component({
selector: 'app-chart',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.scss']
})
export class ChartComponent implements OnInit, OnChanges {
@ViewChild(BaseChartDirective, {read: {selector: 'chart'}, static: false}) baseChart: BaseChartDirective;
constructor(
private hs: HelperService,
private marketService: MarketrateService,
) { }
public lineChartOptions: any
public lineChartPlugins = [zoomPlugin]
public lineChartDataSets: ChartDataSets[] = []
ngOnInit() {
this.lineChartDataSets = [{
data: [],
// label: 'Buy Price',
// backgroundColor: "#2072ef",
// borderColor: '#2072ef',
type: 'line',
pointRadius: 0,
fill: false,
lineTension: 0,
borderWidth: 2,
}]
this.lineChartOptions = {
showTooltip: true,
legend: {
display: false
},
responsive: true,
fill: false,
pan: {
enabled: true,
mode: 'x',
},
zoom: {
enabled: true,
mode: 'x',
},
hover: {
mode: 'nearest',
intersect: true,
onHover: function(e) {
e.target.style.cursor = 'move'
}
},
scales: {
xAxes: [{
gridLines: {
display: false
},
scaleLabel: {
display: false,
labelString: 'Time',
},
type: 'time',
time: {
min: 0,
tooltipFormat: 'DD-MMM-YYYY HH:mm',
displayFormats: {
// 'second': 'MMM DD, hh:mm A',
'second': 'DD/MM/YY HH:mm',
'hour': 'HH:mm',
'day': 'MMM D',
},
round: 'second',
unit: 'hour',
},
distribution: 'series',
ticks: {
source: 'data',
beginAtZero: false,
maxTicksLimit: 7,
autoSkip: true,
maxRotation: 0,
minRotation: 0
},
}],
yAxes: [{
ticks: {
callback: (value) => {
return value.toFixed(this.activePairSettings.denominationCurrencyDisplayDecimalPlaces);
}
},
position: 'right',
gridLines: {
display: false
},
scaleLabel: {
display: false,
labelString: `Prices (${this.qc.toLocaleUpperCase()})`
}
}]
},
tooltips: {
backgroundColor: '#007bff',
intersect: false,
displayColors: false,
color: '#fff',
mode: 'index',
callbacks: {
label: (tooltipItem, myData) => {
// console.log('tooltipItem, myData', tooltipItem, myData)
var label = myData.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
// label += parseFloat(tooltipItem.value).toFixed(6);
label += this.hs.bigNumberWithDecimalPrecision(tooltipItem.value, this.activePairSettings.denominationCurrencyDisplayDecimalPlaces).toString() + ` ${this.qc.toUpperCase()}`
// console.log('label', label)
return label;
}
}
}
}
}
}
html:
<div class="chart">
<div class="card">
<div class="chart-container">
<canvas chart *ngIf="showChart" baseChart [options]="this.lineChartOptions" chartType="line"
[datasets]="lineChartDataSets" [plugins]="lineChartPlugins" >
</canvas>
</div>
</div>
</div>