0

I am trying to write custom directive to pass input values and then bind data to the sparkline chart but it gives me error:

sparkline is not a function.

Below is the plunker:

 import { Directive, ElementRef, HostListener, Input , OnInit } from '@angular/core';

@Directive({
  selector: '[myBarChart]'
})
export class BarChartDirective {
  private el: HTMLElement;

  @Input('myBarChart') barChartValues: number[] = [];

  constructor(el: ElementRef) { this.el = el.nativeElement; }

  ngOnInit() {
  this.el.sparkline(this.barChartValues, {
    type: 'bar', barColor: 'green', width: 300, height: '50',
    barWidth: 8, barSpacing: 3, colorMap: ["green", "yellow", "red"], 
    chartRangeMin: 0
  });
 }
}

http://plnkr.co/edit/BpY6Kd1bSMzWTKSZqJzv

halfer
  • 19,824
  • 17
  • 99
  • 186
VR1256
  • 1,266
  • 4
  • 28
  • 56

3 Answers3

1

You need to move your initialization processing into the ngOnInit lifecycle hook method:

constructor(private el: ElementRef) { 
}

ngOnInit() {
  el.sparkline(this.barChartValues, {
    type: 'bar', barColor: 'green', width: 300, height: '50',
    barWidth: 8, barSpacing: 3, colorMap: ["green", "yellow", "red"], 
    chartRangeMin: 0
  });
}

Values of inputs are only available during the first ngOnChanges right before the ngOnInit but not within the constructor.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Thanks Thierry, but that still did not fixed the issue with sparkline not a function. I updated the plunker. how to fix this sparkline not a function I think even after i referencing the sparkline script in index.html it still not picking it up. – VR1256 Jul 11 '16 at 14:42
0

It's nearly two years later but I here's a solution that works around the fact that Angular doesn't know about the JQuery sparkline function. Simply add declare var $: any; around line 2 of the example code. Then use the JQuery $() syntax in the critical line below:

ngOnInit() {
 $(this.el).sparkline(this.barChartValues, {
   type: 'bar', barColor: 'green', width: 300, height: '50',
   barWidth: 8, barSpacing: 3, colorMap: ["green", "yellow", "red"], 
   chartRangeMin: 0
 });
}

Angular compiles without error.

workerjoe
  • 2,421
  • 1
  • 26
  • 49
0

I am not using directive. Here is a way without using directive. For me its working.

First Move your jquery.sparkline.js to external folder like , "/external/js/jquery.sparkline.js".

Then Use create element like this.

initSparkline(){

    let s = this.renderer.createElement('script');
    s.type='text/javascript';

    // TODO: Move this call to ngDoChange event 
    s.text = "$(function() { setTimeout(function(){ $('#inlinesparkline').sparkline();}, 2000);})";

    this.renderer.appendChild(this.document.body, s);
    }

}

and call it as you want. and in html.

<div id="inlinesparkline">50,60,30,35,25,10,50,20,25,40,45,60,30</div>

I was using angular 4. It should work in angular 2 also

Subhabrata Banerjee
  • 442
  • 1
  • 4
  • 18