3

I need to implement a “select all” option for an Ionic 4 select list. However, I didn't find a way to fire a (click) or similar event from ion-select-option or ion-select. Any suggestions? Note that solutions for Ionic 3 don't necessarily work vor v4.

<ion-item>
  <ion-label>Header</ion-label>
  <ion-select [(ngModel)]="items" multiple okText="OK" cancelText="Cancel">
    <ion-select-option value="all">Select all</ion-select-option>
    <ion-select-option *ngFor="let item of items" [value]="item.id">{{ item.name }}</ion-select-option>
  </ion-select>
</ion-item>
Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45
Roman Volkov
  • 389
  • 1
  • 3
  • 8

2 Answers2

3

Try like this:

Working Demo

.ts

  items;

  constructor() {
    this.options.unshift({
      id: -1,
      name: `Select All`
    });
  }

  onChange(evt) {
    if (evt == -1) {
      this.items = this.options.map(x => x.id);
    } else {
      let selectAllIndex = this.items.indexOf(-1);
      this.items.splice(selectAllIndex, 1);
    }
  }

.html

    <ion-select [(ngModel)]="items" multiple okText="OK" cancelText="Cancel" (ngModelChange)="onChange($event)">
        <ion-option *ngFor="let item of options" [value]="item.id">
            {{ item.name }}
        </ion-option>
    </ion-select>
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
3

You can do this using ViewChild as follows.

HTML

<ion-item>
    <ion-label>Header</ion-label>
    <ion-select #myselect multiple [(ngModel)]="items" okText="OK" 
             cancelText="Cancel" 
            (ngModelChange)="onChange()" 
            (click)="openSelect(myselect)">
      <ion-option [value]="all" (ionSelect)="selectAll(myselect)">{{all}}</ion-option>
    <ion-option *ngFor="let option of options" [value]="option">{{option}}</ion-option>
  </ion-select>
</ion-item>

TS

  items: any = [];

  options = ['A', 'B', 'C'];
  all: string = 'select all';

  @ViewChild('myselect') mySelect: Select;

  selectAll(select: Select){
    let selectInputs = select._overlay['data']['inputs'];
    selectInputs.map((array) => array.checked = true);
  }
  openSelect(select: Select){
    select.open();
  }

When you click OK button there will be select all in selected items array. If you do not need that you can remove it as below inside onChange method when it fires ngModelChange event as below.

onChange() {
  const allIndex = this.items.indexOf(this.all);
  this.items.splice(allIndex, 1);
}

StackBlitz

Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45