Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 use ng-select as an autocomplete field

select from ... in my application. Is it possible to use it as an autocomplete field, the select value is not required. I want to use ng-select because it uses a virtual scroll and the mat-autocomplete from angular material doesn't. And with a lot of values the mat-autocomplete becomes slow.

My question: Is it possible to use the ng-select just as an autocomplete function. In other words: ng-select without the required select option. If I click away from the ng-select field, the value will be empty if nothing selected. The value has to stay..

<label>Your first ng-select</label>
      <ng-select class="custom" [items]="cities"
                bindLabel="name"
                placeholder="Select city"
                [typeahead]="typeahead"
                [(ngModel)]="selectedCity">
      </ng-select>
like image 341
Dev Db Avatar asked May 03 '18 11:05

Dev Db


People also ask

How can I get the selected value of Ng-select?

Add the [(ngModel)] attribute to the attributes of the ng-select , and pass its value to the triggering.

What is the use of NG-select?

AngularJS ng-selected Directive The ng-selected directive sets the selected attribute of an <option> element in a <select> list. The option will be selected if the expression inside the ng-selected attribute returns true. The ng-selected directive is necessary to be able to shift the value between true and false .


1 Answers

I believe you are using

https://www.npmjs.com/package/@ng-select/ng-select#api

it is not recommended to use it that way, how ever there is a work around.

Add the following listeners

(open)= OnOpen(), (search) = OnSearch(), (blur) = OnBlue()

<ng-select [items]="cities" #select1
                   bindLabel="name"
                   (open)= OnOpen()
                   (search) = OnSearch()
                   (blur) = OnBlue()
                   dropdownPosition="hidden"
                   [(ngModel)]="selectedCity">
        </ng-select>

Add define these two variables

isbeingSearched: boolean = false;
@ViewChild('select1') select1Comp: NgSelectComponent;

//Code to handle events

OnOpen(){
  console.log("OnOpen");
  if(!this.isbeingSearched)
  {
    this.select1Comp.close()      
  }

}

OnSearch(){
  this.isbeingSearched = true;
  console.log("OnSearch");
  this.select1Comp.open()
}

OnBlue(){
  console.log("OnBlue");
  this.isbeingSearched = false;
  this.select1Comp.close()
}

Working example

https://stackblitz.com/edit/ng-select-lw4dfh

like image 69
Jeba Prince Avatar answered Oct 06 '22 17:10

Jeba Prince