Search code examples
angularmulti-selectangular-ngselect

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


Solution

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