Hi viewers, In this tutorial i am going to show you how to upload more than one images in ionic app with some additional options like re-ordering the images and deleting the specific uploaded image.

In your .html file add the below code.

<ion-content [fullscreen]="true">
    <!-- image upload, reorder and delete -->
    <ion-reorder-group (ionItemReorder)="doReorder($event)" disabled="false">
      <ion-item *ngFor='let preview of previews; let i=index;'>
          <ion-thumbnail>
            <img [src]="preview" alt="" class="img-padding">
          </ion-thumbnail>
          <ion-reorder color="primary" slot="end"></ion-reorder>
          <ion-icon color="primary" name="close-circle-outline" slot="end" (click)="removeImage(i)"></ion-icon>
      </ion-item>
  </ion-reorder-group>
  <!-- input field for selecting images from local path -->
  <input #image type="file" accept="image/*" hidden multiple (change)="selectFiles($event)" />
  <!-- add button in ionic for above input field -->
  <ion-fab horizontal="end" vertical="bottom" slot="fixed">
      <ion-fab-button (click)="image.click()">
          <ion-icon name="add"></ion-icon>
      </ion-fab-button>
  </ion-fab>
</ion-content>

In your .ts file add the below code.

import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonReorderGroup } from '@ionic/angular';
import { ItemReorderEventDetail } from '@ionic/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  selectedFiles?: any = [];
  progressInfos: any[] = [];
  message: string[] = [];
  previews: string[] = [];
  product_id : number;

  @ViewChild(IonReorderGroup) reorderGroup: IonReorderGroup;
  @ViewChild('image') input: ElementRef;

  constructor() {}

  selectFiles(event: any): void {

    this.message = [];
    this.progressInfos = [];
    this.selectedFiles.push(...event.target.files);
    this.previews = [];
    const numberOfFiles = this.selectedFiles.length;
      
    for (let i = 0; i < numberOfFiles; i++) {
      const reader = new FileReader();
      reader.onload = (e: any) => { this.previews.push(e.target.result); };
      console.log(this.selectedFiles[i]);
      reader.readAsDataURL(this.selectedFiles[i]);
    }
  }

  doReorder(ev: CustomEvent<ItemReorderEventDetail>) {
    this.previews = ev.detail.complete(this.previews);  
    var newArr = this.selectedFiles;
    [newArr[ev.detail.from], newArr[ev.detail.to]]  = [newArr[ev.detail.to], newArr[ev.detail.from]];
  }

  toggleReorderGroup() {
    this.reorderGroup.disabled = !this.reorderGroup.disabled;
  }

  removeImage(a) {
    this.previews.splice(a,1);
    this.selectedFiles.splice(a,1);
  }

}

Leave a Reply

Your email address will not be published. Required fields are marked *