简体   繁体   中英

angular 4 splice always deletes last element from array

I have a weird problem where for some reason splice always deletes last element from array, even though the alert gives correct index.

The onRemove() method is what does the removing.

<button (click)="onAdd()">Add</button>

<ul>
    <li *ngFor="let course of courses; index as i; even as isEven">
        {{ i }} - {{ course.name }} <span *ngIf="isEven">(EVEN)</span>
        <button (click)="onRemove(course)">Remove</button>
    </li>
</ul>

export class AppComponent {

    courses = [
        { id: 1, name: 'course1' },
        { id: 2, name: 'course2' },
        { id: 3, name: 'course3' },
    ];

    onAdd() {
        this.courses.push({ id: 4, name: 'course4' });
    }

    onRemove(course) {
        let index = this.courses.indexOf(course);
        alert(index); // I get correct index here
        this.courses.splice(index, 1);
    }

}

The logic is correct. I think the angle you are looking at it could be the problem. It is removing the correct element when you click on it.

For example, consider that you have 3 elements in the array with the following contexts index starting from 0.

  0 - course1
  1 - course2 
  2 - course3

When You remove element with index 1, the total number of elements becomes two and as a result the index changes as well.

0 - course1 
1 - course3

So this can get you to think that it is always deleting the last element whereas in reality it is just shifting the position of the array.

The following code could be what you are trying to achieve. Just change the first string interpolation to {{course.id}} instead of {{i}}

<li *ngFor="let course of courses; index as i; even as isEven">
    {{ course.id }} - {{ course.name }} <span *ngIf="isEven">(EVEN)</span>
    <button (click)="onRemove(course)">Remove</button>
</li>  

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM