Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any examples for integrating Select2 with Angular2 Components?

I've been trying to find a demonstration/example of how to integrate Select2 into an angular 2 component.

My end goal is to use select 2 ajax features to populate the dropdown as I start typing in the select box aka https://select2.github.io/examples.html#data-ajax

So far my Google ninja powers have failed me :(

Failing examples of select2 integration... are there any other suggestions?

like image 616
andycwk Avatar asked Feb 15 '16 10:02

andycwk


1 Answers

When I started my hunt for Select2 multi drop-down example in Angular2, I couldn't find the kind of one I was looking for. I realized that sometimes Google ninja power doesn't work. I had to write it myself. However, I thought to share it and not let the Google ninja power down again for this. :)

plunker here to see the working demo

The core of this is to wrap the select2 in an angular component.

export class DummySelect {
  constructor(private id: string){
    $(id).select2({
      width: '100%',
      ajax: {
        url: 'https://api.github.com/search/repositories',
        datatype: 'json',
        delay: 250,
        data: function(params: any){
          return {
            q: params.term
          };
        },
        processResults: function(data:any, params: any){
          return {
            results:
              data.items.map(function(item) {
                return {
                  id: item.id,
                  text: item.full_name
                };
              }
            )};
          },
        cache: true  
      },
      placeHolder: 'Search...',
      minimumInputLength: 2 
    })
  }

  getSelectedValues(private id: string){
    return $(id).val();
  }
}
like image 179
Shahid Avatar answered Nov 12 '22 08:11

Shahid