From my yesterdays questions i’ve got another new , well those are pretty easy almost like yesterday ones which they got resolved with your help and my effort so first before all thank you!!!
I will explain my code now:
listaItems: any = [];
i have a provider where i share some items in an arraylist, this arraylist is called listaItems, there i save the exercise when the user presses a button and they get saved there without problem, there is my adding fuction:
pretty easy uh? Well now the problem comes when the user wants to delete that exercise, i thought on using the fuction splice because i didnt find a function like the “remove” function in java, the nearest was this “splice”, i saw that i need the index of the object in the arraylist so that i did:
buscarIndiceDeItem(item) {
var i = 0;
var final = -1;
this.listaItems.forEach(element => {
i++;
if (element.title == item.title) {
//console.log("entramos aqui con i de " + i);
final = i;
}
});
return final;
}
this function is called inside another:
eliminarDeRutina(item) {
var indiceABorrar = this.buscarIndiceDeItem(item);
if (indiceABorrar != -1) {
this.listaItems.splice(indiceABorrar, item);
console.log("borrado con exito");
}
console.log(this.listaItems.length);
}
i somehow get to delete all the items from the same type but i dont want that, i want to delete one item in particular, i got his index and everything just i dont know how to delete it from the arraylist itself!
is it late i already found a solution, not the cleanest and styliest one for sure but i will explain it now:
what i did it was get the this.listaItems array and make an auxiliar array, so now i have 2 arrays and one index
In the auxiliar i copy the same items from the original one except the indexed one so if i had an array of 4 items now i have another of 3 for example, the original one gets removed fully by doing:
this.listaItems=[]
and then i copy the items from the aux to the original one so now both have 3 items and the selected item got deleted, its simple way and not elegant at all im sure, but better than stuck and loosing time!!
Thank you for your answer anyway! u keep want to see the html?
You’re using the splice wrong. The second parameter of the splice method is the count of the delete/splice. So you should enter a numeric value there; 1.
Also, typescript has build in methods for finding an index of an object containing a specific value.
Btw.
I’ve created an Interface which is also cleaner to work with. Creating interfaces for your (data) objects will help you script faster and with less chance for errors.
I’ve created a folder for these; e.g.: [root]/src/models/item.model.ts