Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 653
Mingyue Chen Avatar asked Jul 25 '18 11:07

Mingyue Chen


People also ask

How do I get rid of Clear all in Ng-select?

In your stylesheet add display: none; to the . ng-clear-wrapper selector.

How does ng-select work?

The ng-selected directive sets the selected attribute of an <option> element in a <select> list. The option will be selected if the expression inside the ng-selected attribute returns true. The ng-selected directive is necessary to be able to shift the value between true and false .


2 Answers

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([]);
}
like image 199
mtpultz Avatar answered Jan 03 '23 14:01

mtpultz


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"
like image 20
Zahid Ahmed Avatar answered Jan 03 '23 15:01

Zahid Ahmed