如何清除ng-select选择

Tim*_*Tim 0 angular-ngselect angular

是否可以通过编程方式清除ng-select下拉列表的选择?我想要单击清除图标的等效行为,但是是以编程方式触发的。

ng-select下拉菜单的屏幕截图,其中带有清除图标的红色圆圈

我期待有一种clear()方法或类似的方法,但是文档化的API在这些方面没有任何内容。

这是我的下拉代码:

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

Run Code Online (Sandbox Code Playgroud)

Buc*_*ski 7

这是评论的解决方案:

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

  // Call to clear
  this.ngSelectComponent.handleClearClick();
Run Code Online (Sandbox Code Playgroud)

请注意,handleClearClick文档中未将其公开为公共api方法,但是正如Tim所提到的,它是公共方法,因此可以调用它。

  • `this.ngSelectComponent.clearModel();`,这对我有用。 (2认同)
  • @GSangram 那么你应该使用 `@ViewChildren` 并找到你的特定的。 (2认同)

Ash*_*M A 7

我正在寻找相同的但模板以在外部调用它ng-select。因此,按照接受的答案,以下内容对我来说效果很好。^_^

<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()">
Run Code Online (Sandbox Code Playgroud)

这也确保了resetCalculations()被调用。

  • 这段代码不完整。它没有显示 `resetCalculations();` 包含的内容。哪个是最重要的部分... (3认同)

Tim*_*Tim 6

只需将 ngModel 值设置为 null 即可清除选择。在上面的例子中:

this.selectedCalculation = null;
Run Code Online (Sandbox Code Playgroud)

这与单击清除图标并不完全相同,因为它不会触发(clear)输出事件,但它足以满足我的需求。