3

I want to use 3rd party ui elements/components in my angular2 app like e.g. spin.js. To use this library I would have to directly access the DOM which is not really the way it should be done in angular2 (for several reasons like for example server-side rendering):

var target = document.getElementById('foo') var spinner = new Spinner(opts).spin(target); 

Is there any advice on how to deal with such 3rd party libraries in angular2? Or is direct DOM manipulation the only way for now?

1
  • Can you share your plunker demo because even i am trying to build a directive... so that i can use your code as a reference and proceed...Please sir Commented May 3, 2016 at 2:47

1 Answer 1

4

I would wrap it into a custom directive:

@Directive({ selector: '[spinner]' }) export class SpinnerDirective { constructor(private elementRef:ElementRef.nativeElement) { } ngAfterViewInit() { var spinner = new Spinner(opts).spin(this.elementRef); } } 

and use it this way:

@Component({ (...) template: ` <span spinner>...</span> `, directives: [ SpinnerDirective ] }) export class SomeComponent { (...) } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it worked, except that I had to use elementRef.nativeElement inside the spin method
My component decorator doesn't take a directives argument (using TypeScript). Is this a limitation of TypeScript or is there a different official way to add directives to a component?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.