问题
I have the following component, but I can't print test variable value inside onClick function of Chart.
export class EntradaSaidaComponent {
@ViewChild('graficoDeBarraTemplate')
private graficoDeBarraTemplate;
graficoDeBarra: Chart;
test:any = "Test";
ngOnInit(){
this.graficoDeBarra = new Chart(this.graficoDeBarraTemplate.nativeElement, {
type: 'bar',
data: {
labels: ["Entrada", "Saída"],
datasets: [
{
backgroundColor: ["#00b050", "#00b0f0"],
data: [this.dashboard.totalReceber, this.dashboard.totalPagar],
label: this.sharedProvider.formatMoeda(this.dashboard.totalReceber)
},
{
backgroundColor: ["#03A9F4"],
data: [],
label: this.sharedProvider.formatMoeda(this.dashboard.totalPagar)
},
]
},
options: {
responsive: true,
plugins: {
},
legend: {
display: true,
position: 'bottom'
},
onClick: function(){
console.log(this.test);
},
},
});
}
}
How to solve it?
回答1:
Use the arrow function
onClick: () => {
console.log(this.test);
},
回答2:
Context issue.
Either (yes, this is a strange syntax for an object, but trust me it works)
onClick(){
console.log(this.test);
},
Or
onClick: () => console.log(this.test),
来源:https://stackoverflow.com/questions/56806373/acess-component-variable-inside-onclick-function-of-chart-js