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?

3
  • Have you seen any or all of stackoverflow.com/q/36173678/3001761, npmjs.com/package/angular2-select2, npmjs.com/package/ng2-select2 Commented Nov 16, 2016 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 stackoverflow.com/a/35055539/5922900 Look that dropdown function comes from 'semantic' library which was imported as well. Commented Nov 16, 2016 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. Commented Nov 16, 2016 at 16:44

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

What I was trying to do is the same as what was done with semantic at: stackoverflow.com/a/35055539/5922900 Look that dropdown function comes from 'semantic' library which was imported as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.