Splice cannot remove first element in javascript

In angular2, my HTML is calling removeThisForm in javascript. The event is an object of an array of files. For each object in an array of files, I am generating a form in angular2.

(click)=removeThisForm(event)

      

In javascript, I am trying to delete a file that is passing through.

removeThisForm(file) {
    var removableIndex = arr.indexOf(file);
    if (removeIndex >= 0) {
        arr = arr.splice(removableIndex);
    } 

      

I can delete any shape except the first one. I tried shift (), slice () and splice (0,1). When I did the splice (0,1), I get the error "Form submission canceled because the form is not connected".

+3


source to share


1 answer


You missed the second argument to the Array.prototype.splice method (an integer representing the number of elements to remove). Try the following:

removeThisForm(file) {
    var removableIndex = arr.indexOf(file);
    if (removeIndex >= 0) {
        arr.splice(removableIndex, 1);
    } 
}

      

In addition, the method Array.prototype.splice

returns an array containing the removed elements. Therefore, you cannot say:



arr = arr.splice(removableIndex, 1);

      

as it will override yours arr

with the return value of the method Array.prototype.splice

.

+5


source







All Articles