Components variable were changed by modal

Hello,

I have a variable from my component (array variable) that contains pdfs and images. I am passing that variable to a modal and it filters the variable to display only the images and to remove the pdfs (and it is working fine). The problem is that after I closed the modal my variable on the component page was also changed.

Page Component

public files: any = [image1.jpeg, file.pdf, image2.jpeg]

openModal() {
  console.log(files); // result: [3] => [image1.jpeg, file.pdf, image2.jpeg]
  var imageParams = {
    'url' : files,
  }
  var modal = this.modalCtrl.create("ModalImageDisplayPage", {imageParams: imageParams});
  modal.onDidDismiss(() => {
    console.log(files); // result: [2] => [image1.jpeg, image2.jpeg] **The pdf has been removed here, it should not be removed. The 'files' variable should not be changed!!**
  })
  modal.present();
}

Modal Component

public imageUrl: any = [];

constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController) {
  var imageParams = navParams.get('imageParams');
  this.imageUrl = imageParams['url'];

  for (var x = 0; x < this.imageUrl.length; x++) {
    if (this.imageUrl[x].includes('.pdf')) {
      this.imageUrl.splice(x, 1);
      console.log(imageUrl); // result: [2] => [image1.jpeg, image2.jpeg] **The pdf has been removed here. It should be the variable to be changed NOT THE 'files' variable!!**
    }
  }
}

The point is the files variable in the Page Component should not be changed and the imageUrl variable is the only variable that should be changed.

I hope someone can help me with this. Thank you :slight_smile:

The documentation for splice clearly states that it modifies the array in place, so it seems you have two options:

  • pass a clone of the array
  • don’t use splice
1 Like

Try this

If (this.imageUrl.includes(’.pdf’))
{
var sample = this.imageUrl.splice(x, 1);
console.log(sample);
}

I’m not seeing how that would address OP’s concerns.

Well pardon me my code isn’t what I was trying to convey please do ignore @rapropos @OliverPrimo

I will come up with clear version of my code

Thank you for the idea. I got this to work by cloning the array. Hehe