Skip to content
This repository has been archived by the owner on Jun 7, 2022. It is now read-only.

How to do backend search in ng select2

Stijn Goethals edited this page Aug 13, 2019 · 1 revision

Step 1 : component.html

<ng-select2 id="select2ID" name="select2ID" [options]="remoteOptions" 
  (valueChanged)="onValueChange($event)" [(ngModel)]="selectedID">
</ng-select2>

Step 2: component.ts

//Declare globally.
public remoteOptions: Options;
public selectedID: any;

bind remote options inside ngOnInit()

 ngOnInit() {

    this.remoteOptions = {
      multiple: false,
      width: "100%",
      theme: 'bootstrap',
      minimumInputLength: 1,
      placeholder: {
        id: "",
        placeholder: 'Search Item...',
      },
      allowClear: true,
      ajax: {
        url: <<Your API URL>>,
        dataType: 'json',
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer <<Your API Access Token if have otherwise skip this >>`
        },
        data: function (params) {
          return {
            q: params.term,
          };
        },
        processResults: function (data, params) {

          //Here data must have array of objects which have "id" & "text" property 	  
          return {
            results: data
          };
        },
        cache: true
      },
      escapeMarkup: function (markup) { return markup; },
      templateResult: this.formatResult,
      templateSelection: this.formatSelection
    }
  }

define two more methods formatResult & formatSelection.

formatResult(d) {
    return d.text;
 }

formatSelection(d) {
    if (d.id == null || d.id == "" || d.id == undefined) {
      return "Search Item..."; //Default Place holder
    }
    return d.text;
 }

onValueChange(event) method is call when value of the drop-down changes

onValueChange(event) {
   console.log(event);
}

Reference Links:

Clone this wiki locally