jQuery-Select2 with Angular, Multiple Selection and Default Selection

2019-10-09

jQuery-Select2 is a awesome library that is custom select box with support for searching.

With Angular

First, install jQuery and select2 with npm.

npm install --save jquery select2

Then, load sources in angular.json.

"styles": [
"node_modules/select2/dist/css/select2.min.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.js",
"node_modules/select2/dist/js/select2.min.js"
]

Next, install a library that is Angular wrapper for Select2 with npm

npm install --save ng2-select2

Add the following in app.module.ts.

import { Select2Module } from 'ng2-select2';
@NgModule({
imports: [
Select2Module
],
})

Finally, it works well with the following.

<select2
  [data]="selectData"
></select2>
import { Select2OptionData } from 'ng2-select2';
selectData: Array = [
    {
      id: '1',
      text: 'hoge'
    },
    {
      id: '2',
      text: 'fuga'
    }
  ];
}

Case of Multi-select boxes

If you want to use multi-select with select2, add “multiple: true" to options as the following.

<select2
  [data]="selectData"
  [options]="selectOptions"
></select2>
import { Select2OptionData } from 'ng2-select2';
  selectOptions = {
    multiple: true
  }
}

Case of setting a Default Value

If you want to set a default value, set “id" value to “[value]".

<select2
  [data]="selectData"
  [value]="defaultValue"
></select2>
import { Select2OptionData } from 'ng2-select2';
  defaultValue = ['1'] //"id" of data
}

Select2 is extremely awesome!