如何添加“全选"在Angular 5中进行ng-select的功能 [英] How to add "select all" functionality to ng-select in Angular 5
问题描述
我找到了一个可以全选"的例子: https://ng-select.github.io/ng-select#/多选复选框
I found an examle which can do "select all": https://ng-select.github.io/ng-select#/multiselect-checkbox
但是,我收到一个错误:Cannot read property 'selected' of undefined.
我想知道为什么会出现此错误,以及如何在Angular 5中使用ng-select实现全选".
But, I get an error: Cannot read property 'selected' of undefined.
I am wondering why I got this error, and how to implement "select all" using ng-select in Angular 5.
谢谢
推荐答案
在Angular 5中使用ng-select
会限制您使用ng-select
的 v1.6.3 (或< v2.x) ,但是您可以使用ng-select
标头模板完成此操作.我在下面添加了代码,但这是一个有效的
Using ng-select
in Angular 5 limits you to using v1.6.3 of ng-select
(or < v2.x), but you can accomplish this using the ng-select
header template. I included the code below, but this is a working Stackblitz I put together as an example:
<ng-select [items]="listOfItems"
bindValue="id"
bindLabel="name"
[multiple]="true"
placeholder="Select City"
formControlName="example">
<ng-template ng-header-tmp>
<div>
<button class="btn btn-link"
(click)="onSelectAll()">Select All</button>
<button class="btn btn-link"
(click)="onClearAll()">Clear All</button>
</div>
</ng-template>
</ng-select>
然后,在控制器中,您将使用一系列值映射来修补表单控件,这些值映射为仅包含您提供给ng-select
的绑定值,即bindValue
键值.
Then in your controller you would patch the form control with an array of values mapped to only include the bound values you provided to ng-select
, which are the bindValue
key values.
public onSelectAll() {
const selected = this.listOfItems.map(item => item.id);
this.form.get('example').patchValue(selected);
}
public onClearAll() {
this.form.get('example').patchValue([]);
}
这篇关于如何添加“全选"在Angular 5中进行ng-select的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!