Zone Constraints for Dragging and Dropping in Angular 8

Seeking help to solve a puzzling issue that has been occupying my thoughts for the past few days.

The Challenge

I am attempting to incorporate a drag-and-drop functionality that allows users to drag up to 10 items and place them in specified spots (each spot can only hold one item). Once all 10 spots are filled, dragging more items should not be allowed until a spot is cleared.

Currently, I am utilizing the Ngx-Smooth-DND library for drag-and-drop, but I am open to exploring other libraries such as Kendo Sortable if they meet the requirements.

The Issue lies in the fact that the drag-and-drop feature allows multiple items in a list/zone, while I want to restrict it to only one item per zone. Think of it like a quiz where you drag an answer to a specific spot on a diagram - once placed, either replace it by dropping another item or keep the spot empty.

What's Needed

I need to implement a drag-and-drop system where users can drag items from a list of options and drop them into one of ten different zones.

  • Variable number of draggable options
  • 10 Drop Zones
  • Each zone can only have 1 item at a time

Code Snippet

Linking a Stackblitz demonstration of what I am aiming for, along with the Ngx-smooth-dnd library documentation:

https://stackblitz.com/edit/angular-ro3pyw

https://github.com/kutlugsahin/ngx-smooth-dnd

Extra

If there is a more efficient or simpler approach or drag-and-drop library that can achieve this task better, I am completely open to suggestions.

Answer №1

Utilizing angular material components, I was able to achieve a similar outcome by implementing drag and drop functionality. You can find more information on angular material drag and drop here: https://material.angular.io/cdk/drag-drop/overview

In order to restrict the number of items that can be present in a container, I referred to this specific example: https://material.angular.io/cdk/drag-drop/overview#controlling-which-items-can-be-moved-into-a-container

// drop-example.component.html
<div class="drop-area" cdkDropList
  #dropArea="cdkDropList"
  [cdkDropListData]="myEmptyArrayVariable"
  [cdkDropListConnectedTo]="[optionsList]"
  (cdkDropListDropped)="drop($event)"
  [cdkDropListEnterPredicate]="limiterPredicate">
// drop-example.component.ts
import { CdkDragDrop, moveItemInArray, transferArrayItem, CdkDrag, CdkDropList } from '@angular/cdk/drag-drop';

...
// Please refer to the drag-drop docs for the implementation of the drop($event) {} function
...

limiterPredicate(item: CdkDrag, container: CdkDropList) {
  if (container.data.length === 0) {
    return true;
  } else {
    return false;
  }
}

If you encounter any challenges with the code, feel free to reach out and I can create a stackblitz demo for you!

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

How can you merge two arrays with identical property values in Javascript?

Is there a way to combine arrays with the same property value without using map due to different indexes? var array1 = [ {'label':"label1",'position':0}, {'label':"label3",'position':2}, {&ap ...

Newbie exploring the world of Rails and jQuery

While I am making progress with jQuery and successfully linking js.erb files to controller actions, I have encountered a roadblock. I am unsure of how to make a button, which is not associated with a controller action, trigger specific jQuery commands. My ...

Display real-time information in angular material table segment by segment

I need to incorporate service data into an Angular mat table with specific conditions as outlined below: If the difference between the start date and end date is less than 21 days, display 'dd/mm' between the 'start_date' and 'end ...

Mastering the Art of Trimming with Jquery

function DisplayDataForEdit(id) { $("#editContainer").slideDown("medium"); var parentId ='item'+ id; var colIndex = 0; var $row = $("#" + parentId).parent().parent(); $row.find('td').each(f ...

Ways to enhance the type definitions for a built-in HTML element in Vue.js?

Imagine having an element that wraps around an input and inherits all of its properties, along with some extras. In React, you would define this as: interface ExtendedInputProps extends React.ComponentPropsWithoutRef<'input'> { some: T ...

Issue with TypeScript: 'MongoClient' variable cannot be resolved

Just dipping my toes into TypeScript, I decided to convert a JavaScript file to TypeScript using WebStorm for the very first time. Although my code is functional, I keep receiving this warning: unresolved variable 'MongoClient' Additionally, ...

When RxJS returns an empty observable, it does not trigger the successful action

I am working with a Rxjs effect that has the following structure: callApiPostSyncPushEffect$ = createEffect(() => { return this.actions$ .pipe( ofType(SyncActions.callApiPostSyncPushPullAction), mergeMap((action) ...

Modify the JSON file stored on the local server

I am currently working on a project that is being hosted on a local server. My main objective is to be able to edit and save a JSON file that will contain the configurations for this project. I have succeeded in reading the file and accessing it using axio ...

An error has occurred in Node.js: SyntaxError - Unexpected token ]

Here is the code snippet I am working with: app.get("/posts/:slug", function(request, response) { var slug = request.params.slug; connection.query("SELECT * from `posts` WHERE slug = ?", [ slug ], function(err, rows) { var post = rows[]; ...

I have incorporated jquery-1.2.6.js into my project but I am encountering difficulties utilizing the live method

C# foreach (DataRow Row in oDs.Tables[0].Rows) { LitPreferances.Text += "<Li ID=LI_" + Row["pk_Preference_Branch_ID"].ToString() +"_"+ Row["pk_Preference_BranchType_ID"].ToString() +">" + Row["Branch_Name"].ToString() + "&nbsp;&nbsp;< ...

Issue with reading the current length of an array object in a while loop in Angular 6

After successfully splitting an array into parts, I decided to add some filters to only include the items in the list that have an action status of (4). However, I encountered a problem where the while loop couldn't read the length of the array. This ...

Bootstrap encountered an issue with altering header information

I've been trying to set up a notification system that plays a sound every time someone makes a new post. I'm working with Bootstrap 4 and I've tried inserting JavaScript into the functions page, but no matter how many times I call the ' ...

Region Covered by Mouse Over Does Not Extend Across Whole Div

On my website, there is an arrow located on the middle right side that, when hovered over with the mouse, reveals a sidebar. Clicking on each icon in the sidebar further extends it to reveal more content. However, the issue I am facing is that the sidebar ...

Looking for a JavaScript equivalent to Dart's millisecondsSinceEpoch functionality

A new chat system is being developed to connect mobile and web platforms using firestore. The challenge at hand involves the sorting of documents based on timestamp, as those created from both mobile (using flutter) and web (using vue js) are not in ascend ...

Setting up Mailgun with TypeScript on Firebase Cloud Functions

Currently, I am working on a Cloud Function within Firebase to integrate with Mailgun for sending emails, following the guidelines provided in the Mailgun documentation. My challenge lies in implementing this functionality using TypeScript, as I have been ...

Utilize regular expressions on a JSON response dataset

Imagine a scenario where a client makes a GET request and the response is in JSON format similar to the following: var result = { "enabled": true, "state": "schedule", "schedules": [ { "rule": { "start": "2014-06-2 ...

Discover records that include the specific object id within an array (Mongodb)

I'm currently tackling a node project and struggling with using the find() function on an array of object ids. Let me share an example of a document stored in my mongodb database: { "_id": { "$oid": "6515923586714e6ae70 ...

Determine whether an element is currently focused using a Vue.js directive

I'm attempting to verify if an element is currently in focus, specifically an input field, and then apply a class to another element. This is the code I have been working on, but for some reason the hasFocus() function isn't functioning as expect ...

Animating the display and concealment of a Ui Bootstrap alert within an AngularJS modal window

Trying to create a dynamic animation for an ng-hide feature used on a Ui Bootstrap alert button within a Ui Bootstrap Modal is proving to be quite challenging. The goal is to have the alert slide in and out while simultaneously fading in and out. Although ...

Does adding the async attribute to a script impact the timing of the onload event?

I am facing an issue with a webpage that contains a script tag in the HEAD section: <script src="somescript.js" type="text/javascript" async></script> Since it has the async attribute, this script loads asynchronously, allowing the browser to ...