0

I have some <select class='select'>'s in a @Component.

I'm following a template which styles every select with a third-party library called Select2. The HTML + jQuery + Select2 code is:

$( document ).ready(function() {
    $('.select').select2();
});

I was wondering if it would be a good idea to create a directive for doing this, so I tried:

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

@Directive({
  selector: '[simple-dropdown]'
})
export class SimpleDropdownDirective {

  constructor(el: ElementRef) {
    $(el.nativeElement).select2();
  }

}

But I'm getting error on the select2() method. Since it's a third-party library I don't think I can install it as I've done with jQuery.

What would you suggest?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Pasp Ruby
  • 957
  • 1
  • 9
  • 22
  • Have you seen any or all of http://stackoverflow.com/q/36173678/3001761, https://www.npmjs.com/package/angular2-select2, https://www.npmjs.com/package/ng2-select2 – jonrsharpe Nov 16 '16 at 16:11
  • @jonrsharpe Yes. Select2 was only an example of third party library. I'm facing the same issue with different libraries. I was wondering if I could import select2.js so I could make my Directive example work, as in http://stackoverflow.com/a/35055539/5922900 Look that dropdown function comes from 'semantic' library which was imported as well. – Pasp Ruby Nov 16 '16 at 16:20
  • Inevitably *"how do I interface with any third party library"* is going to be too broad. If you could show the specific error you get in the current code that might help to solve this specific issue. – jonrsharpe Nov 16 '16 at 16:44

1 Answers1

0

Select2 depends on jQuery, so this will not work out of the box.

When you use jQuery to select an element, you don't get a native Element, but the jQuery enhanced element. You have the option to port Select2 to Angular 2 or get it to work with native browser APIs like querySelectorAll. (You can try to make a feature request to the author as well, but as Select2 states itself as jQuery dependant, I would not bet on getting it implemented.)

Thomas
  • 11,272
  • 2
  • 24
  • 40
  • What I was trying to do is the same as what was done with semantic at: http://stackoverflow.com/a/35055539/5922900 Look that dropdown function comes from 'semantic' library which was imported as well. – Pasp Ruby Nov 16 '16 at 16:22