How to clear ng-select selection

前端 未结 8 1258
孤街浪徒
孤街浪徒 2021-02-19 07:21

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

相关标签:
8条回答
  • 2021-02-19 07:59

    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 = [];
      }
    
    0 讨论(0)
  • 2021-02-19 08:04

    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.

    0 讨论(0)
提交回复
热议问题