Updating an array of drag and drop elements in Angular Material

During my attempt to use drag and drop functionality with Angular Material, I encountered an issue with updating the `pos` key in a JSON array. Specifically, I wanted to set the `pos` value to the value of `event.currentIndex` while also adjusting the position values of other items in the array.

component.ts

import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

temp: number;

movies = [
    {name: 'Episode I - The Phantom Menace', pos: 0},
    {name:'Episode II - Attack of the Clones', pos: 1},
    {name: 'Episode III - Revenge of the Sith', pos: 2},
    {name: 'Episode IV - A New Hope', pos: 3}
  ];

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.movies, event.previousIndex, event.currentIndex);
    console.log(this.movies[event.currentIndex]);
    console.log(this.movies);
    this.temp = event.previousIndex;
    event.previousIndex = event.currentIndex;
    event.currentIndex = this.temp;
    this.movies[event.currentIndex].pos = event.currentIndex;
    this.movies[event.previousIndex].pos = event.previousIndex;
  }

component.html

<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
    <div class="example-box" *ngFor="let movie of movies;" cdkDrag>
        {{movie.name}} {{movie.pos}}
    </div>
</div>

Initial list

https://i.sstatic.net/HSMWC.png

After swapping

https://i.sstatic.net/IqOlR.png

This issue occurs when dragging either the first or last item in the list.

What adjustments should be made to the code?

Answer №1

As previously mentioned by Avishek, the code

moveItemInArray(this.movies, event.previousIndex, event.currentIndex);
is used to sort an array. One simple approach to save these changes is to iterate through your collection and update their positions based on their index in the array.

for( let i = 0; i < this.movies.length; i ++){
        this.movies[i].position = i
      }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Angular: How to access ViewChild from a dynamically loaded component

One of my components includes a ViewChild element like this: @ViewChild('overView') content: ElementRef; I am dynamically loading this component in the following way: let overviewComponent = this.vcr.createComponent(OverviewComponent); let conte ...

Obtain the firebase object using Angular framework

Hey there, I've been working on retrieving a Firebase object using Angular and have successfully achieved that. However, I'm now faced with the challenge of how to navigate deeper into the data that is being returned (check out the images linked ...

The Angular application is not able to initiate the POST request

I have developed a database to store game data. Through testing, I have found that adding a "team" to a "game" functions correctly. However, my Angular application is not successfully triggering the database. I have verified that the database operation wo ...

Passing intricate data structures from Angular to a C# Controller

I've encountered an issue with my service that sends requests to an MVC controller in C#. Everything was working smoothly until I tried to send a complex object. The parameter postDto in C# always ends up being null. I have attempted various solution ...

What is the process for accessing my PayPal Sandbox account?

I'm having trouble logging into my SandBox Account since they updated the menu. The old steps mentioned in this post Can't login to paypal sandbox no longer seem to work. Could someone please provide me with detailed, step-by-step instructions o ...

Sorting arrays of objects with multiple properties in Typescript

When it comes to sorting an array with objects that have multiple properties, it can sometimes get tricky. I have objects with a 'name' string and a 'mandatory' boolean. My goal is to first sort the objects based on age, then by name. ...

Tips on how to combine or flatten arrays using rxJS

I am looking to consolidate a structured array into one uniform array. The original array structure is as follows: [ { "countryCode": "CA", "countryName": "Canada", "states": [ { "stateCode": "CAAB", "stateName": "Alber ...

Countdown component in Ant Design failing to display correct date

I’m currently working on developing a specific date component using react in conjunction with antd. Below is the code snippet I am utilizing: import { Statistic, Col, Row } from 'antd'; const { Countdown } = Statistic; const deadline = Date.pa ...

Typescript disregarding conditional statements

Looking for some assistance with a Next.JS React-Typescript application Here's my code snippet for handling the video HTML element const videoRef = useRef<HTMLVideoElement>(); useEffect(() => { videoRef !== undefined ? videoRef.current. ...

Running your Angular application on a Node server: Step-by-step guide

I am looking to deploy my application using express on a Node server. This is the content of my server.js file: var express = require('express'); var path = require('path'); var app = express(); app.get('/', (req, res) => ...

Having trouble with Angular 2 not properly sending POST requests?

Having some trouble with a POST request using Angular 2 HTTP? Check out the code snippet below: import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import 'rxjs/add ...

Having trouble creating a dynamic form in Ionic

I am in need of creating a dynamic form. Here is the desired output: {"laboratories":[{"colArr":[{"col":"11"},{"col":"22"},{"col":"33"}]},{"colArr":[{"col":"5"},{"col":"423"}]}]} The key laboratories represents the number of rows. Each row contains the k ...

The types 'X' and 'string' do not intersect

I have a situation where I am using the following type: export type AutocompleteChangeReason = | 'createOption' | 'selectOption' | 'removeOption' | 'clear' | 'blur'; But when I try to compress the cod ...

Using react-hook-form to easily update form data

While working on my project with react-hook-form for updating and creating details, I encountered a problem specifically in the update form. The values were not updating properly as expected. The issue seems to be within the file countryupdate.tsx. import ...

Error with Array type encountered in Typescript's find method

I am encountering an issue with code that looks like this: type X = { test: number; x: number; }[]; type Y = { test: number; y: number; }[]; type Z = { test: number; z: number; }[]; export const testFunc = (arg: X | Y | Z) => { return a ...

Issue with react-native-svg ForeignObject missing in project (React Native with Expo using TypeScript)

I am working on a React Native project in Expo and have incorporated the expo TypeScript configuration. Using "expo install," I added react-native-svg version 9.13.3 to my project. However, every time I attempt to render the SVG using react-native-svg, I ...

Exploring Angular RxJS: the art of filtering Observable arrays

Is there a way to effectively filter an array Observable in Angular? I am working with an observable Array: announcementList$: Observable<Announcement[]> = this.announcementService.getAnnouncement(0,0).pipe(filter(Boolean),shareReplay(), map(({data} ...

Tips for handling numerous buttons in ionic?

I'm currently working on an app that includes surveys. In this app, users are required to answer by selecting either the Yes or No button. The desired behavior is for the chosen button to turn blue once clicked, while the other button should maintain ...

Using jQuery in Angular, you can add a div element to hidden elements by appending

So, I have a hidden div that I want to show on button click. And not only do I want to show it, but I also want to append another div to it. The show and hide functionality is working fine, but the appending part seems tricky when dealing with hidden eleme ...

Developing custom events in an NPM package

Developing a basic npm package with signalr integration has been my recent project. Here's how it works: First, the user installs the package Then, the package establishes a connection using signalr At a certain point, the server triggers a function ...