简体   繁体   中英

Ionic 3 - remove images from an ion-slides with help of .getActiveIndex()

I have added images from gallery/camera to an ion-slider view.I have an action sheet which gives me an option to add or remove the images from the slider view.Adding is working fine as i am adding that image to array and providing that updated array to the slider. But for removing an image i need to get the index of the image that is active on the slider and after that i need to remove it. I m not able to get the active index using this code :

onSlideChanged() {
     try{
      let currentIndex = this.slides.getActiveIndex();
      console.log("Current index is", currentIndex);
     }catch(e){
       console.log("not able to get the active index");
     }   }

this also goes into the catch part. Then im removing the first element from the array and updating the array for slider.The array size is reduced when i press the delete button from action sheet but all the images in the slider disappears leaving a blank space.

<div *ngIf="field.value" (click)="takePicture(field.name)">
     <ion-slides pager="true" style="max-height:500px" (ionSlideDidChange)="onSlideChanged()">
     <ion-slide *ngFor="let c of field.value">
     <img class="image-attach" [src]="c" draggable="true">
     </ion-slide>
     </ion-slides>
      </div>
      <canvas #latlon style="display:none"></canvas>
    </div>

code for setting images to the slider

removePicture(name) {
    for (let i = 0; i < this.formType.template.secs.length; i++) {
      for (let d = 0; d < this.formType.template.secs[i].fields.length; d++) {

        if (this.formType.template.secs[i].fields[d].name == name) {

        if(this.formType.template.secs[i].fields[d].value.length>1)
        {
          this.formType.template.secs[i].fields[d].value.splice(this.currentIndex,1);
          this.attachedImagesArray.splice(this.currentIndex,1);
          console.log(this.formType.template.secs[i].fields[d].value.length);
          var arr = this.formType.template.secs[i].fields[d].value;
          console.log("^^^^^^^",arr);
          this.formType.template.secs[i].fields[d].value = this.formType.template.secs[i].fields[d].value;
        }
        else{
        console.log("*********",this.formType.template.secs[i].fields[d].value);
        this.formType.template.secs[i].fields[d].value = "";
        }
      }
    }
    }
  };

this is the code im using for removing the images from slider. I m new to ionic so don't know why this is happening, i googled for it but nothing worked for me.

for putting the images to the slides im using the following code :

selecPicture(name) {
    this.camera.getPicture({
      quality: 50,
      destinationType: this.camera.DestinationType.FILE_URI,
      targetHeight: 500,
      targetWidth: 500,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
    }).then((imageData) => {

      //alert(imageData);
      // imageData is a base64 encoded string DATA_URL FILE_URI 'lat: '+lat+', lon: '+lon,
      let base64Image = "data:image/jpeg;base64," + imageData;

      this.geolocation.getCurrentPosition().then((resp) => {
        let lat = resp.coords.latitude;
        let lon = resp.coords.longitude;
        this.lat = lat;
        this.lon = lon;
        let d = new Date();
        let draftSavedTime = d.toString().substr(4, 11);
        let canvas = this.canvasRef.nativeElement;
        let context = canvas.getContext('2d');
        console.log(context);
        console.log("hello");
        let newImg = new Image();
        newImg.src = imageData;
        newImg.onload = () => {

          canvas.setAttribute("width", newImg.height);
          canvas.setAttribute("height", newImg.width);
          // context.drawImage(newImg, 0, 0);
          context.drawImage(newImg, 0, 0, newImg.width, newImg.height);
          // context.font = "15px impact";
          context.font = "bold 13px Arial";
          // context.textAlign = 'center';
          context.fillStyle = 'red';
          context.fillText(draftSavedTime, 20, 20);
          // context.fillText('Lat: '+lat+'     Lon: '+lon, canvas.width / 2, canvas.height * 0.9);
          context.fillText('Lat: ' + lat, canvas.width * 0.1, canvas.height * 0.8);
          context.fillText('Lon: ' + lon, canvas.width * 0.1, canvas.height * 0.9);
          // context.fillText('Lon: '+lon, canvas.width / 2, canvas.height * 0.8);
          let image = canvas.toDataURL();
          this.attachedImages.push(image);
          this.setValue(name, image);

    };
      }).catch((error) => {
        console.log('Error getting location', error);
      });
    }, (err) => {
      console.log(err);
    });
  }

to set the value of image in the field : //to set the value in the field

setValue(name, data) {

    console.log(this.attachedImages);
    console.log(this.formType.template.secs); //3
    for (let i = 0; i < this.formType.template.secs.length; i++) {
      console.log(this.formType.template.secs[i].fields); //2
      for (let d = 0; d < this.formType.template.secs[i].fields.length; d++) {
        if (this.formType.template.secs[i].fields[d].name == name) {

          this.attachedImagesArray.push({
            name : this.formType.template.secs[i].fields[d].name,
            image : data,
            number : d
          });


var group_to_values = this.attachedImagesArray.reduce(function (obj, item) {
    obj[item.name] = obj[item.name] || [];
    obj[item.name].push(item.image);
    return obj;
}, {});

var imageGroup = Object.keys(group_to_values).map(function (key) {
    return {key: key, image: group_to_values[key]};
});

var pre = document.createElement("pre");
pre.innerHTML = "imageGroup:\n\n" + JSON.stringify(imageGroup, null, 4);
document.body.appendChild(pre);


var newArr = [];
newArr.push({imageGroup});

for(var item in newArr)
{
  console.log(newArr[item]);
  for(var sec in newArr[item])
  {
    console.log(newArr[item][sec]);
  }

  for( var elm in newArr[item][sec])
  {
    console.log(newArr[item][sec][elm]);
  }

  for( var key in newArr[item][sec][elm])
  {
    this.arrNameStr = newArr[item][sec][elm].key;
    console.log(newArr[item][sec][elm].image);
  }
}

console.log(this.arrNameStr);
if(this.arrNameStr.includes(this.formType.template.secs[i].fields[d].name))
{
  console.log(newArr[item][sec][elm].image);
  console.log(this.formType.template.secs[i].fields[d].value);
  this.formType.template.secs[i].fields[d].value = newArr[item][sec][elm].image;
  console.log(this.formType.template.secs[i].fields[d].value);
}
  }
}
  }
};

First ensure that you get this event firing off and that your reference to the slides element in the template returns the Slides: (ionSlideDidChange). Do:

onSlideChanged() {
    console.log(this.slides)
}

Your console should return reference to the slides element.

It is unclear how you obtain this reference based on your code, but seeing you have *ngIf directive there is a chance you are not actually able to get it since the element doesn't exist at init stage of the component.

To fix that you can pass reference to ion-slides in the ionSlidesChanged method:

<div *ngIf="field.value" (click)="takePicture(field.name)">
     <ion-slides #mySlides (ionSlideDidChange)="onSlideChanged(mySlides); mySlides.update()" pager="true" style="max-height:500px">
         <ion-slide *ngFor="let c of field.value">
             <img class="image-attach" [src]="c" draggable="true">
         </ion-slide>
     </ion-slides>
 </div>

Now in the actual method you should be able to get the value of currentIndex:

onSlideChanged(mySlides) {
    let currentIndex = mySlides..getActiveIndex();
    // here do splice or whatever manipulation you need with your data source / array
}

Let me know if this helped.

UPDATE: since there is a need to refresh slides UI after the change to the model it is good to call "update" method: (ionSlideDidChange)="onSlideChanged(mySlides); mySlides.update()".

Template is now updated with this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM