Mingyue Chen
Mingyue Chen

Reputation: 95

How to add "select all" functionality to ng-select in Angular 5

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

Upvotes: 7

Views: 19729

Answers (3)

Zahid Ahmed
Zahid Ahmed

Reputation: 61

Using ng-select multi select with group by - you can add "select all" functionalities with an easy way. Here is the full example -

Demo : https://angular-mkv8vp.stackblitz.io

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

Step 1- call the method for select all group by - this.selectAllForDropdownItems(this.people);

Step 2- add selectedAllGroup to every items of that array for group by.

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

    allSelect(items);
  };
  1. then bind to html
  • groupBy="selectedAllGroup" [selectableGroup]="true"

Upvotes: 5

Margi212
Margi212

Reputation: 153

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

Upvotes: 2

mtpultz
mtpultz

Reputation: 18268

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

Upvotes: 24

Related Questions