Angular array object drag and drop functionality

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


@Component({
  selector: 'kt-menu-management',
  templateUrl: './menu-management.component.html',
  styleUrls: ['./menu-management.component.scss']
})
export class MenuManagementComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
  items = [
    {
      id:1, name:'Appetizer'
    },
    {
      id:2, name:'Main Course'
    }
   ]

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.items, event.previousIndex, event.currentIndex);
  }
}

Sample demo available here : https://stackblitz.com/angular/omybvaablxk?file=src%2Fapp%2Fcdk-drag-drop-custom-placeholder-example.ts

**Looking for guidance on implementing Angular drag and drop functionality for an array of objects. I've tried it with an array of strings successfully, but not with an array of objects. Attempts using interfaces have also been unsuccessful. Any suggestions?

**

Answer №1

To implement a custom placeholder in your cdk-drag-drop-custom-placeholder-example.html, simply make the following modification:

<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let movie of movies" cdkDrag>
    <div class="example-custom-placeholder" *cdkDragPlaceholder></div>

    {{movie.title}}       -------------->  Change this to iterate over object titles.

  </div>
</div>

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

Retrieving the value that is not currently selected in a mat-select component

In my mat-table, there is a mat-select component displayed like this: <mat-select multiple placeholder="{{element.name}}" [(value)]="selectedCol" (selectionChange)="selectionChange($event)" [disabled]="!selection.isSelected(element.id)"> & ...

The event triggered by the tinymce editor does not immediately refresh the Angular Component

I am currently working on creating an Angular application using a WordPress instance of TinyMCE. Within the editor, there are non-content-editable elements that trigger a modal window to open when clicked. However, I have encountered an issue where the mo ...

Join and Navigate in Angular 2

Attempting to retrieve information from a JSON file has been an issue for me. Here is the code snippet: ngOnInit() { this.http.get('assets/json/buildings.json', { responseType: 'text'}) .map(response => response) .subsc ...

Using the ternary operator will always result in a TRUE outcome

Having trouble with a ternary operator expression. AssociatedItemType.ExRatedTag ? session?.data.reloadRow(ids) : this.reloadItemRows(this.prepareItemsIdentities(ids)!), The AssociatedItemType is an enum. I've noticed that const ? 1 : 2 always retur ...

The database is receiving new information, however, it is not being visually represented on the frontend

After making updates to my user details, I noticed that the changes are reflected in the collection data but not on the page when I refresh. However, upon logging out and back in, the updated information is displayed correctly. For some reason, the compone ...

Validating Firebase data for null values

Hey there, I'm currently working on a simple coding project but seems to be encountering some roadblocks. The main objective of the code is to determine if a username exists in the system or not. Here's a snippet of the data structure and codes ...

Swapping out a knockout observable that is passed as an argument

When passing two observables as parameters, I am attempting to replace them with another observable. However, for some reason, the replacement does not occur, even though changing the value on the observable works. private searchAndReplace = (flag: string ...

Display a React functional component

Greetings, friends! I recently created a React app using functional components and now I am looking to print a specific page within the app. Each page is its own functional component, so I was wondering if it's possible to print a component individual ...

The property 'class' is required for ".builders['browser']"

Upon successfully installing the dependencies using npm install, I encountered an error while attempting to run the server: Schema validation failed with the following errors: Data path ".builders['browser']" should have required property ' ...

Using TypeScript in Angular to make a function call can result in an endless loop being created

In my current use case, I am aiming to update the array in both the if and else scenarios. The primary array, referred to as cis, appears as follows: https://i.sstatic.net/esbb8.png .html <sample-container [cis]="filterCi(currentBaseline.cis, c ...

Transitioning from AngularJS to Angular: Updating the factory prototype

I've been in the process of migrating from AngularJS to Angular and have made a lot of progress. However, I am currently facing challenges with factories and prototypes. In this context, the Card object represents a playing card. function Car ...

Filtering dates using the Angular Material Date filter on a single adapter

After implementing a custom date format for my mat-datepicker, I encountered a specific challenge: export const PICK_FORMATS = { parse: {dateInput: {month: 'short', year: 'numeric', day: 'numeric'}}, display: { date ...

A guide on combining two native Record types in TypeScript

Is it possible to combine two predefined Record types in TypeScript? Consider the two Records below: var dictionary1 : Record<string, string []> ={ 'fruits' : ['apple','banana', 'cherry'], 'vegeta ...

The Angular Progressive Web App functions properly in ng serve mode, but encounters issues when running with http-server

I'm developing a Progressive Web App (PWA) using Angular. Everything was functioning smoothly until out of nowhere, I started encountering a 404 Error whenever I tried to navigate to a new component while serving in dist/project with http-server. Surp ...

An issue arose during the compilation of aot with Angular 4

While attempting to compile the application with the following command ng build --prod --aot` or `ng build --aot An error is encountered as shown below EDIT After trying the suggested fix by @Obed . A new error is generated ERROR in Error dur ...

Creating scrollable Material tabs

In my application, I am utilizing Material tabs (using mat-tab elements inside a mat-tab-group). When there are too many tabs to be displayed at once, two navigation buttons appear to allow access to the other tabs: https://i.sstatic.net/i7Vhh.png I am l ...

Despite the presence of a producer and topic, sending Kafka messages is proving to be a challenge

Currently, I am using TypeScript and the KafkaJS library on my local machine with a single Kafka broker. After successfully connecting a producer, confirming the creation of my topic, and creating messages like so: const changeMessage = { key: id, ...

The Rule of Indentation in SonarLint for TypeScript

I'm a beginner when it comes to SonarLint rules and I've been trying to locate the rule for indentation and variable naming in TypeScript rules, but haven't had any luck. While I was able to find naming rules for classes and functions, I co ...

Which programming language or technology utilizes the syntax <%VARIABLE%> and in what context is it employed?

First things first, I want to clarify that I'm not a developer, so this might be a simple question. Despite my research indicating that ASP typically uses this syntax, it's important to note that it is not the case here. I am currently delving i ...

Failed deployment of a Node.js and Express app with TypeScript on Vercel due to errors

I'm having trouble deploying a Nodejs, Express.js with Typescript app on Vercel. Every time I try, I get an error message saying "404: NOT_FOUND". My index.ts file is located inside my src folder. Can anyone guide me on the correct way to deploy this? ...