如何在 Angular 5 中向 ng-select 添加“全选”功能

Min*_*hen 3 multi-select angular-ngselect angular

我找到了一个可以“全选”的例子:https : //ng-select.github.io/ng-select#/multiselect-checkbox

但是,我收到一个错误:Cannot read property 'selected' of undefined. 我想知道为什么我会收到这个错误,以及如何在 Angular 5 中使用 ng-select 实现“全选”。

谢谢

mtp*_*ltz 15

使用ng-select你在角5个限制使用1.6.3版本ng-select(或<V2.X),但可以这样使用完成ng-select报头模板。我包含了下面的代码,但这是我放在一起作为示例的有效Stackblitz

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

然后在您的控制器中,您将使用映射到仅包含您提供给的绑定值的值数组修补表单控件ng-select,这些bindValue值是键值。

public onSelectAll() {
  const selected = this.listOfItems.map(item => item.id);
  this.form.get('example').patchValue(selected);
}

public onClearAll() {
  this.form.get('example').patchValue([]);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

使用 ng-select 多重选择和分组依据 - 您可以通过简单的方法添加“全选”功能。这是完整的例子 -

演示: https: //angular-mkv8vp.stackblitz.io

代码:https://stackblitz.com/edit/angular-mkv8vp?file=src/ multi-checkbox-group-example.component.html

步骤1-调用选择所有分组依据的方法-this.selectAllForDropdownItems(this.people);

步骤 2-将 selectedAllGroup 添加到该数组的每个项目中作为分组依据。

selectAllForDropdownItems(items: any[]) {
    let allSelect = items => {
      items.forEach(element => {
        element['selectedAllGroup'] = 'selectedAllGroup';
      });
    };

    allSelect(items);
  };
Run Code Online (Sandbox Code Playgroud)
  1. 然后绑定到html
  • groupBy="selectedAllGroup" [selectableGroup]="true"