Search code examples
angularchart.jstooltip

Angular-ChartJs : Use a service inside a custom tooltip of a graphic chartJs


I am trying to use an angular service inside a custom tooltip. Inside my custom tooltip, I put something like this :
....
tooltipEl.innerHTML = 'Title ' + this.myService.getTitle() + '';
....

I have this error : ERROR Error: Cannot read property 'getTitle' of undefined

That because THIS is not recongnized inside the custom tooltip.

My question is, how can I call myService inside the tooltip ?

Thanks.

I prepare an example example here : https://stackblitz.com/edit/ng2-charts-tooltip-border-ibkso



public pieChartOptions: ChartOptions = {
responsive: true,
tooltips: {
        // Disable the on-canvas tooltip
        enabled: false,

        custom: function(tooltipModel) {
          console.log(tooltipModel)
            // Tooltip Element
            var tooltipEl = document.getElementById('chartjs-tooltip');

            // Create element on first render
            if (!tooltipEl) {
                tooltipEl = document.createElement('div');
                tooltipEl.id = 'chartjs-tooltip';
                tooltipEl.innerHTML = '<table class="myclass">Title ' + this.myService.getTitle() + '</table>';
                document.body.appendChild(tooltipEl);
            }

            // Hide if no tooltip
            if (tooltipModel.opacity === 0) {
                tooltipEl.style.opacity = '0';
                return;
            }

            // Set caret Position
            tooltipEl.classList.remove('above', 'below', 'no-transform');
            if (tooltipModel.yAlign) {
                tooltipEl.classList.add(tooltipModel.yAlign);
            } else {
                tooltipEl.classList.add('no-transform');
            }

            function getBody(bodyItem) {
                return bodyItem.lines;
            }

            // Set Text
            if (tooltipModel.body) {
                var titleLines = tooltipModel.title || [];
                var bodyLines = tooltipModel.body.map(getBody);
                // console.log("tooltipModel", tooltipModel.body)
                var innerHtml = '<thead>';

                titleLines.forEach(function(title) {
                    innerHtml += '<tr><th>' + title + ' ToTo</th></tr>';
                });

                innerHtml += '</thead><tbody>';
                // console.log(bodyLines)
                bodyLines.forEach(function(body, i) {
                    var colors = tooltipModel.labelColors[i];
                    var style = 'background:' + colors.backgroundColor;
                    style += '; border-color:' + colors.borderColor;
                    style += '; background-color: red';
                    style += '; border-width: 10px';
                    var span = '<span style="' + style + '"></span>';
                    innerHtml += '<tr><td>' + span + body + '</td></tr>';
                    console.log(body)
                });
                innerHtml += '</tbody>';

                var tableRoot = tooltipEl.querySelector('table');
                tableRoot.innerHTML = innerHtml;
                // console.log(tableRoot)
            }

            // `this` will be the overall tooltip
            var position = this._chart.canvas.getBoundingClientRect();

            // Display, position, and set styles for font
            tooltipEl.style.opacity = '1';
            tooltipEl.style.position = 'absolute';
            tooltipEl.style.backgroundColor = 'white'
            tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
            tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
            tooltipEl.style.fontFamily = tooltipModel._bodyFontFamily;
            tooltipEl.style.fontSize = tooltipModel.bodyFontSize + 'px';
            tooltipEl.style.fontStyle = tooltipModel._bodyFontStyle;
            tooltipEl.style.padding = tooltipModel.yPadding + 'px ' + tooltipModel.xPadding + 'px';
            tooltipEl.style.pointerEvents = 'none';
        }
    }

Solution

  • When inside a function, this refers to the inner scope of the function.

    To call refer outside the scope of a function using this, you should use an arrow function.

    tooltips: {
      custom: (tooltipModel) => {
        // will refer to the myService instance outside of this function
        const title = this.myService.getTitle(); 
      }
    }
    

    Additionally, you shouldn't be modifying the DOM manually when you're using Angular, apart from in exceptional circumstances. Does this library not offer a way to set the tooltip via the API?