Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear ng-select selection

Tags:

Is it possible to programmatically clear the selection of an ng-select dropdown? I'm wanting the equivalent behaviour of clicking the clear icon, but triggered programmatically.

Screenshot of ng-select dropdown, with clear icon circled in red

I was expecting a clear() method or something similar, but the documented API doesn't have anything along those lines.

This is my dropdown code:

<ng-select class="ng-select-wrap"            [searchFn]="multiTermSearch"            [items]="calculationOptions"            placeholder="Please select..."            name="calculation"            #calculationValue="ngModel"            [(ngModel)]="selectedCalculation"> </ng-select>  
like image 445
Tim Avatar asked Jun 18 '19 09:06

Tim


People also ask

How do I remove the clear icon from Ng-select?

In your stylesheet add display: none; to the . ng-clear-wrapper selector.

What is clearable in Ng-select?

if 'clearable' property is set to false, and clearOnBackspace is set to true, user can remove single item using backspace button. if (this.filterValue || (!multiple && ! this.clearable) || ! this.clearOnBackspace || ! this.hasValue) { template example: <ng-select> (add)=... (

How does ng-select work?

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 .

How do you focus on Ng-select?

Go to 'ng-select component and search something you get some option regarding it. ' Click OR select the option. And after the selection the value Cursor focus out from the component.


2 Answers

Here is solution from comment:

  // Access ng-select   @ViewChild(NgSelectComponent) ngSelectComponent: NgSelectComponent;    // Call to clear   this.ngSelectComponent.handleClearClick(); 

Note that handleClearClick isn't exposed in docs as public api method however as Tim mentioned it's public method so it's possible to call it.

like image 68
Buczkowski Avatar answered Oct 06 '22 07:10

Buczkowski


I was looking for the same but for templates to invoke it outside ng-select. So, the below worked fine for me following the accepted answer. ^_^

<ng-select class="ng-select-wrap"            [searchFn]="multiTermSearch"            [items]="calculationOptions"            placeholder="Please select..."            name="calculation"            (clear)="resetCalculations();"            [(ngModel)]="selectedCalculation" #selectDropdown> </ng-select>  <input type="button" (click)="selectDropdown.handleClearClick()"> 

This also makes sure the resetCalculations() being called.

like image 40
Ashok M A Avatar answered Oct 06 '22 08:10

Ashok M A