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)
}
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);