Home > Net >  Angular How can I remove an object from FileList
Angular How can I remove an object from FileList

Time:06-07

I have an application in angular where I select photos and put them on a array. But I want to be able to delete an item from the table based on a condition. What should i do?

I tried the splice function but i get syntax error.

Here is the code:

//Images
selectedFiles?: FileList;
deleteImage(preview: any){

    //Check at SelectedFile
    if(flag == false){
      if (this.selectedFiles && this.selectedFiles[0]) {
        const numberOfFiles = this.selectedFiles.length;
        for (let i = 0; i < numberOfFiles; i  ) {
         if(this.selectedFiles[i].name == preview.imageName){
          // this.selectedFiles.splice(1,2) PROBLEM
         }
        }
      }
    }

    console.log(this.previews)
  }

CodePudding user response:

Your issue is you are iterating over the array while changing it.

So, if you go index 0, 1, 2 in that order... but on 1 you remove one value. You would go:

1st iteration -- [a, b, c] // you target index 0: a

2nd iteration -- [a, b, c] // you target index 1: b and remove it

3rd iteration -- [a, c] // you target index 2: undefined.. you get syntax error because you cant this.selectedFiles[i].name as you are doing undefined.name

Your solution would be to either locally save which indexes will be removed on the iteration, and AFTER the iteration remove them.. or iterate the way you are doing, but remove i-- inside your if (so you actually repeat the index after removal -- repeat index 1 in my example, after removing b from that index).

If you are removing 2, then i -= 2, etc...

Hope this makes sense

PS: in my opinion, doing i-- is weaker than saving indexes on iteration and then removing. It leads to more bugs. Also, you could check to use filter function and simply reasign a filtered array.

this.selectedFiles = this.selectedFiles.filter(file => file.imageName !== preview.name);

CodePudding user response:

The reason you get a syntax error is that a FileList is not an array, and it doesn't have array properties/methods (to be more precise, it barely has any properties/methods: length, item(), and that's it).

https://developer.mozilla.org/en-US/docs/Web/API/FileList

If you want to manipulate it, start with conversion to an array:

filesArray: File[] = [...this.selectedFiles];

Then, I suggest Francisco's filter approach (instead of explicit iteration) for the actual solution.

  • Related