Murhaf Sousli
Murhaf Sousli

Reputation: 13296

angular2 get the selector reference of a component

I'm trying to integrate this library progressbar.js in angular2 app, the way this library works that you have to add the progressbar to a container by passing the selector name

var ProgressBar = require('progressbar.js');

// Assuming we have an empty <div id="container"></div> in HTML

var bar = new ProgressBar.Line('#container', {easing: 'easeInOut'});
bar.animate(1);  // Value from 0.0 to 1.0 

The problem here is when I want multiple progress-bars and each one should be contained in its own component otherwise all the progress-bars will be added to the same container (which is not what I want)

var ProgressBar = require('progressbar.js');
@Component({
  selector: 'progress-bar',
  template: `<div class="#pb-container"> </div>`
})
export class ProgressBarCmp {

  @Input() color;
  @Input() strokeWidth;

  ngOnInit() {
    this.bar = new ProgressBar.Circle('#pb-container', {      
      color: color,
      strokeWidth: strokeWidth,
    });
    this.bar.animate(this.skill.grade / 100);
}

Should I have a unique ID for each component or is there an angular way to fix this problem?

Upvotes: 0

Views: 2864

Answers (1)

Murhaf Sousli
Murhaf Sousli

Reputation: 13296

Thanks to @JBNizet comment, problem was solved by passing this.elementRef.nativeElement instead of #pb-container

var ProgressBar = require('progressbar.js');
@Component({
  selector: 'progress-bar',
  template: ''    // <= no need for a container anymore 
})
export class ProgressBarCmp {

  @Input() color;
  @Input() strokeWidth;

  constructor(private elementRef:ElementRef){
  }

  ngOnInit() {
    this.bar = new ProgressBar.Circle(this.elementRef.nativeElement, {      
      color: this.color,
      strokeWidth: this.strokeWidth,
    });
    this.bar.animate(this.skill.grade / 100);
}

Upvotes: 2

Related Questions