Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement Multi Select feature (Long press/Hold and select) in Ionic

I am working on an Ionic project having a list. I want a multi-select feature just like the hold and select feature in android gallery, so that upon long press checkboxes appear in front of list items, enabling me to select more than one item.

Any suggestions on how to implement that? I am not looking for GalleryView feature but just long press and select feature, just like it.

Is it possible without creating actual checkboxes? Or do I need to create checkboxes and implement the on-hold event?

Note: For those who are confusing whether I want to implement android gallery feature, please pay attention! I DO NOT want to implement android gallery feature here. I only want to implement a MULTI-SELECT feature on simple list in the same way we select multiple images on long press in android gallery, or even take an example of selecting multiple contacts in contact list, etc.

like image 416
Dhruv Singhal Avatar asked Nov 07 '22 07:11

Dhruv Singhal


1 Answers

Try this -

<ion-header>
<ion-navbar color="primary">
<ion-title>Notifications</ion-title>
<ion-buttons end *ngIf=selection>
  <button ion-button tappable (click)=disableSelect()>
    <ion-icon name="close" style="zoom:1.5;"></ion-icon>
  </button>
  </ion-buttons>
 </ion-navbar>
</ion-header>

<ion-content padding>
 <div *ngFor="let notification of notifications; let i=index" tappable text-wrap (click)=!selection?toggleGroup(i):selectItem(i,notification)
 (press)=selectItem(i,notification) [ngStyle]="{'background-color': notification.isSelected ? '#f2f2f2' : '#ffffff'}">
 </div>
</ion-content>

And for the typescript

export class NotificationPage {
notifications = new Array<Notification>();
selection: boolean = false;

constructor() {}

public selectItem(index: number, notification: Notification) {
   this.selection = true;
   notification.isSelected = !notification.isSelected;
   this.notifications[index] = notification;
 }

public unselectAll() {
   this.selection = false;
   this.notifications.forEach(notification => {
     notification.isSelected = false;
   });
  }
}

I use two variables, first one is in the model class named isSelected. Its purpose is to determine whether a particular item is selected or not. Also, the item styling is done using [NgStyle] based on the same flag. And second is in the page itself named selected. Its purpose is to make necessary changes in UI after selecting an item.

like image 90
Ashutosh Sagar Avatar answered Nov 14 '22 21:11

Ashutosh Sagar