How to add “select all” functionality to ng-select in Angular 5

时间秒杀一切 提交于 2019-12-07 22:39:09

问题


I found an examle which can do "select all": https://ng-select.github.io/ng-select#/multiselect-checkbox

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.

Thank you


回答1:


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>

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([]);
}



回答2:


If you do not use react forms, and wanted to use select all property, then #getModelValue="ngModel" inside ngselect tag in html file and in *.ts file, add following code:

onSelectAll(select: NgModel, values, array) { 
  const selected = this.dropdownList.datas.map(item => item.id);
  select.update.emit(selected); 
}

deselectAll(select: NgModel) {
     select.update.emit([]); 
}


来源:https://stackoverflow.com/questions/51518133/how-to-add-select-all-functionality-to-ng-select-in-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!