How to clear ng-select selection
Asked Answered
D

10

33

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>

Defoliate answered 18/6, 2019 at 9:54 Comment(0)
R
50

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.

Renae answered 18/6, 2019 at 10:37 Comment(5)
This causes focus on selected input.Hove
this.ngSelectComponent.clearModel();, this works for me.Contrapuntal
I have multiple instance of ng-select. How to detect and clear a particular one ?Heteroclite
@Heteroclite then you should use @ViewChildren and find your particular one.Renae
@Heteroclite you can still use @ViewChild if you're just selecting one. For instance, @ViewChild(NgSelectComponent) autocompleteField: NgSelectComponent; will select for an element tagged like this in your template: <ng-select #autocompleteField></ng-select>. Add whichever other properties you're using on your select already, just add ensure there's a key hash with a name matching the declared variable name in the component.Drongo
B
13

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.

Brandon answered 19/11, 2019 at 3:27 Comment(1)
This code is incomplete. It doesn't show what resetCalculations(); contains. Which is the essential part...Sanctum
D
6

Clearing the selection can be achieved by simply setting the ngModel value to null. In the case of the above example:

this.selectedCalculation = null;

This isn't exactly the same as clicking the clear icon, as it doesn't trigger the (clear) output event, but it was sufficient for my needs.

Defoliate answered 18/6, 2019 at 9:54 Comment(3)
Ultimately you can get ng-select through @ViewChild and call handleClearClick but it isn't good way since it wasn't exposed in public api methods.Renae
@Renae I would prefer your approach. The method isnt marked as private or anything Consider to add it as an answerKnitwear
I am not sure, using this approach actually will not triggered ng-select (change) eventPardon
H
4

Even thought @Buczkowski answer clears ng-select, it also does a focus on input, which isn't needed for all cases. So i used other method: clearModel

  // Access ng-select
  @ViewChild(NgSelectComponent) ngSelectComponent: NgSelectComponent;

  // Call to clear
  this.ngSelectComponent.clearModel();

So if you need to just clear input, use clearModel method. Else if focus and clear is needed, use handleClearClick.

Hove answered 8/1, 2020 at 13:36 Comment(0)
D
2

The best answer is for clearing an input field on a specific action. I also use this code in my project according to my requirement.

In HTML write this code:

<ng-select [items]="products" #ngSelectComponent
           bindLabel="name"
           placeholder="Enter Product Name /SKU/ Scan Barcode"
           appendTo="body"
           name="selectedProduct"
           id="selectedProduct"
           (change)="productChange($event)"
           [multiple]="false"
           ([ngModel])="selectedProduct" >

<input type="button" (click)="clearValue()">

In .TS file add a ViewChild for this control so that if your screen consists of multiple ngSelect elements then you can clear a specific ngSelect value.

@ViewChild('ngSelectComponent') ngSelectComponent: NgSelectComponent;

clearValue(){
  this.ngSelectComponent.clearModel(); 
  // This line will clear the value of ngSelect control. 
  // You can write code according to your requirement.
}
Doublespace answered 23/1, 2021 at 19:23 Comment(1)
I want to clear ngSelect after scan barcod from productDoublespace
H
1

Assuming the originally posted code sample below.

<ng-select class="ng-select-wrap"
           [searchFn]="multiTermSearch"
           [items]="calculationOptions"
           placeholder="Please select..."
           name="calculation"
           #calculationValue="ngModel"
           [(ngModel)]="selectedCalculation">
</ng-select>

The selectedCalculation variable is created as an array and not a string, as the ng-select can allow for multiple values to be selected if [multiple]="true" is set.

To clear the selected value(s) in the array programmatically, use:

this.selectedCalculation = [];

Should you need to clear the bound items, use:

this.calculationOptions = [];

Both of the above can be done by adding the (change) handler in HTML.

(change)="change($event)

Something like this in your TypeScript.

change(event: any): void {
   this.calculationOptions = [];
   this.selectedCalculation = [];
  }
Harman answered 11/11, 2019 at 13:26 Comment(0)
F
0

Like @tim answer is correct but I will prefer you set as an empty array instead of null just to save any loop break.

this.selectedCalculation = [];
Folkrock answered 18/6, 2019 at 10:1 Comment(1)
Not sure if I've misunderstood what you mean, but in this scenario selectedCalculation isn't an array, it's the string value (so in the screenshot selectedCalculation would equal 'abc').Defoliate
V
0

Agree with @tim and @AlexOnozor, I have successfully used 'selectedCalculation' as 'string', 'string[]', 'object[]' with Reactive Forms ( and as 'string' with ngModel ) and your suggested method worked smoothly. I also tried using 'handleClearClick' but failed. Will update if i find my way through it.

So, this.selectedCalculation = '' or this.selectedCalculation= [] (for multipleSelect = true) should work.

Velour answered 11/11, 2019 at 8:29 Comment(0)
L
0

I had the same issue and realised that the only thing that you need to do is to set your calculationOptions that you assign [items] to be an empty array i.e [] in your .ts file.

Now, its seems like you are asking someone set your calculationOptions to []. Its make sense why the clear() functionality does not exist.

Logistics answered 19/5, 2021 at 14:16 Comment(0)
E
0

This worked for me

HTML

  <nz-select
        nzPlaceHolder="Select an Address"
        formControlName="addressId"
        #NzSelectAddress
      >
        <nz-option
          *ngFor="let address of addresses"
          [nzValue]="address.id"
          [nzLabel]="address.city"
        ></nz-option>
      </nz-select>

TS

@ViewChild('NzSelectAddress') NzSelectAddress: NzSelectComponent;
this.NzSelectAddress.onClearSelection();
Embrasure answered 1/5, 2023 at 10:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.