Search code examples
arraysangularmoveangular7

Angular 7 move objects in array results in -1 index, will not save position


So I'm working on a task board and I am making a button to move the selected task to the top/bottom of that container. It is working fine, but not saving the position and when I reload it is in the previous position. I noticed that when I am doing this, the array has a -1 index at the end. I've searched online for this issue but couldn't find anything similar.

Here is the code I have for the function:

public moveToBottom(container, index) {
this.container = container;
var lastIndex = (this.container.length -1);
this.loader.show();
transferArrayItem(this.container, this.container, index, lastIndex);

// this.verifyOrder(lastIndex);
this.loader.hide();
console.log(index, lastIndex, container)

I'm thinking it has something to do with the container.length -1, but this is the only way I've seen to get the last index. I just need the number of the index, not the actual object.

Any help would be appreciated! Thanks!


Solution

  • You just have to use transferArrayItem function.

    For example, there is an array of movies this.movies. So, the button click function will look like this:

    moveToTheEnd(index) {
        moveItemInArray(this.movies, index, this.movies.length - 1);
    }
    

    And HTML:

    <div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
      <div *ngFor="let movie of movies; let index = index" style="display: flex; align-items: center">
          <div class="example-box"  cdkDrag>{{movie}}</div>
          <div (click)="moveToTheEnd(index)" style="background: red">Move to the end</div>
      </div>
    </div>
    

    Here is the example: https://stackblitz.com/edit/angular-vkwb8v