Troubleshooting a Custom Pipe Problem in Angular Material Drag and Drop

Currently, I am working on a project involving Angular Material Drag And Drop functionality. I have created a simplified example on StackBlitz which you can access through this link: here

The project involves two lists - one containing pets and the other containing boxes. Users can drag pets and drop them into different boxes. Each box has a limit of how many pets it can contain.

The current setup works fine! However, I would like to enhance it by adding a custom pipe that dynamically filters each list. For instance, users should be able to filter only cats or pets named Rex.

Being relatively new to Angular and JavaScript/TypeScript, I came across a piece of code that helps in creating a custom pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'listFilter'
})
export class ListFilterPipe implements PipeTransform {
  
  // Code for filtering items here
   
}

In addition to this, I also utilized the example provided in Angular Material's Documentation for handling the Drag And Drop event:

// Code for dropping items here

While the functionalities seem to be working correctly, there is an issue with the way items are handled when applying a filter. The problem arises when a filtered pet is dragged and dropped into a box; the wrong pet is moved. This discrepancy seems to be linked to the index of the unfiltered list used during the drop event.

I am unsure about how to resolve this issue. Any insights or recommendations would be greatly appreciated.

An illustration of the problem can be seen in this gif:

https://i.sstatic.net/4pDOI.gif

Your assistance in resolving this matter would be highly valued. Thank you.

Answer №1

Hey there, I encountered a similar issue and after thorough research, I managed to solve it. In this particular situation, you can utilize the touchend event and mousedown event on the card by passing the current item and the array.

The following code is tailored for mobile touch screens using the touchend event:

<div*ngFor="let item of array">
<div (touchend)="dragTouchEndEvent(array,item)">
</div>
</div>

For desktop browsers, you can employ the (mousedown) event like so:

<div*ngFor="let item of array">
    <div (mousedown)="dragTouchEndEvent(array,item)">
    </div>
    </div>

Don't forget to declare a variable:

 previousIndex:number;

In the TypeScript file of that component, add the following:

 dragTouchEndEvent(itemArray, item) {
    this.previousIndex = itemArray.findIndex(e => e === item);
  }

Then, replace event.previousIndex with this.previousIndex and make sure to clear your search filter:

 someMethod(event: CdkDragDrop<any>) {
        if (event.previousContainer === event.container) {
              moveItemInArray(event.container.data, this.previousIndex, event.currentIndex);
            } else {
              transferArrayItem(event.previousContainer.data,
                event.container.data,
                this.previousIndex,
                event.currentIndex);
    
            }
//clear your search filter here
}

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

The process of setting up a carousel for tables using jQuery

I can successfully implement jquery for an image carousel, but now I need to find a way to create a sliding table format. Any assistance on this matter would be greatly appreciated. Here is the code I currently have: <ul> <li><a style= ...

Server has sent an Ajax response which needs to be inserted into a div

I have a modal window that sends a POST request to the server. Before returning to the view, I store some information in ViewData. Here's an example of what I'm doing: ViewData["Msg"] = "<div id=\"msgResponse\" class=\"success ...

Deleting query strings from the URL - HashRouter

In my application, I have a LoginContainer component that houses both a login-form and a signup-form. These components are displayed on the same page, with only one of them being rendered based on user interaction. While the functionality of the forms is ...

The custom FontAwesome icon is failing to display properly

UPDATE : Here is the StackBlitz as requested. A custom SVG icon was created based on instructions provided by FontAwesome's collaborator found here. Despite mirroring the exact element structure of FontAwesome's icons, the custom icon does not ...

Utilizing async await in a JavaScript event: A guide

I have coded the introduction page for my game, which includes a submit button and a textbox for users to input their username. Upon pressing the submit button, the code posts the name into a JSON file and retrieves all the data from the JSON file to sen ...

Expanding form fields dynamically with AngularJS

I am currently working on a form that allows users to click a '+' sign in order to add new lines. I've set up a function to be called when the button is clicked, which should push a new line into the array. However, for some reason the new l ...

Having trouble mocking Node fs Modules using Sinon

I am facing an issue with mocking the promises methods of the node fs module in my code. When my appData.ts file is executed, it calls the actual fs.promises.mkdir method instead of the mock function defined in \__tests__/appData.test.js. I suspect ...

Modify visibility or enable state of a text box according to a checkbox in PHP

Currently, I am utilizing PHP to exhibit a vertical list of numbered checkboxes, with one checkbox for each day in a specific month. Next to every checkbox, there is a text box where users can input optional notes for the selected day. To ensure that users ...

Encountered an issue while constructing Angular project: Error - EINVAL: invalid argument, mkdir

While attempting to compile my (outdated) Angular project, I encountered this error message Error: EINVAL: invalid argument, mkdir 'C:\Users\me\Documents\project\dist\C:\Users\me\Documents\project&bsol ...

Is there a way to access the Express parameters within my React component?

Currently, I am in the process of developing a React application that utilizes Express as its back-end infrastructure My express route is configured as follows app.get('/manage/:id', (req, res) => { // redirect to react application }); ...

Vuex getters not displaying expected values in computed properties until entire page has finished loading

When working with computed properties using data fetched by the mapGetters function in my Vuex store, I always encounter the issue of getting an undefined value until the entire page or DOM is fully loaded. For instance, I have an example of an isRegister ...

I am unable to view the GridView features that have been set using jQuery in the JavaScript code on the webpage

I'm facing an issue with the properties of a GridView. On the aspx page, I have a container using a <div>. <div id="DivRecords"> Within this container, I am dynamically adding a GridView using jQuery. In the js file, I am creating the Gr ...

`Troubleshooting Firebase Cloud Functions and Cloud Firestore integration`

I previously used the following Firebase Database code in a project: const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value'); Now, I am attempting to convert it for Firestore. My goal is to retrieve my users' ...

ReactJS with Redux Form and Material UI framework featuring automatic typing and field clearing capabilities

Currently, I am in the process of developing a nested form framework that utilizes both the redux form and material ui frameworks. The components are already built up to this point - you can view them here: https://codesandbox.io/s/heuristic-hopper-lzekw ...

What is the proper way to import the Database class from BetterSqlite3 in a TypeScript project?

I am currently working on code that utilizes better-sqlite3 and my goal is to convert it to typescript. The original javascript code includes the following relevant sections: import Database from "better-sqlite3"; /** * @param {string} filenam ...

Retrieving the necessary key values from a JSON dictionary

I'm attempting to retrieve keys from a dictionary using JavaScript. The user uploads a .json file containing the dictionary, and I want to display the keys from that uploaded dictionary. It's important to note that only .json dictionaries can be ...

Step-by-step guide on how to configure the URL path in an AJAX function call

How can I dynamically set the URL path in an AJAX function call when clicking on a page so that the page name is included in the URL? For example, if I click on a particular page (let's say the "ask" page on Stack Overflow), the URL should look like: ...

The Angular selector is unrecognized: double-check that it belongs to the current module if it is an Angular component

After creating a component, I attempted to utilize it in another component by specifying its selector in the display segment. <app-component1></app-component1> However, I encountered a compile error. Upon reviewing the imports in the modules, ...

Deleting an element from HTML using jQuery

In the midst of creating a system that allows users to construct their own navigation structure, I have encountered a stumbling block. The idea is that when a user lands on the site, they are presented with a list of available topics from which they can ch ...

Troubleshoot my code for clustering markers on a Google map

I'm currently working on a piece of code to generate a Google map that contains 3 hidden points within one marker. The idea is that when the main marker is clicked, these points will either merge into one or expand into 3 separate markers. However, I& ...