Step-by-step guide on how to stop CDK Drop depending on a certain condition

I'm trying to figure out how to disable dropping using CDK based on certain conditions. Specifically, I want the drop functionality to be disabled if the list I'm attempting to drop into is empty. I haven't been able to find a solution within my .ts file methods. While there are some HTML directives that could potentially help with this issue, they aren't suitable for my needs.

if(event.container.data.length==1){
  event.previousContainer.disabled=true;
}

I came across the .disabled method for dragged containers, but it only seems to work when dragging. What I need is an event trigger for dropping.

https://stackblitz.com/edit/angular-ui7u9m?file=src/app/cdk-drag-drop-disabled-sorting-example.ts

In the stackblitz example provided, there are two lists. For instance, if the 'Available' list is empty (no elements in the array), dropping should no longer be allowed into this list. Can anyone assist me in achieving this functionality?

Answer №1

To determine whether an item can be moved into a drop container using Angular Material, you can utilize the enterPredicate from CdkDropList. For more information, check out the official documentation.

@Input('cdkDropListEnterPredicate')

enterPredicate: (drag: CdkDrag, drop: CdkDropList) => boolean

This function specifies if an item is allowed to be moved to a drop container.

For example:

HTML:

<div
      cdkDropList
      [cdkDropListData]="basket"
      class="example-list"
      (cdkDropListDropped)="drop($event)"
      [cdkDropListEnterPredicate]="canDrop">
      <div class="example-box" *ngFor="let item of basket" cdkDrag>{{item}}</div>
    </div>

Component:

canDrop() {
    return this.basket && this.basket.length > 0;
}

View the working example on Stackblitz.

Update 1:

You can also access the list where the item was dropped:

canDrop(item: CdkDrag, list: CdkDropList) {    
    console.log(list.getSortedItems().length)
    return list && list.getSortedItems().length && list.getSortedItems().length > 0;
}

Update 2:

An alternative approach is to override the function with a parameter:

...
[cdkDropListEnterPredicate]="dropListEnterPredicate(basket)">
...
dropListEnterPredicate(list: []){
    return function(drag: CdkDrag, drop: CdkDropList) {
        return list.length > 0;
    };

Answer №2

To enable dragging on an element, utilize the cdkDragDisabled property along with the cdkDrag directive.

<div *ngFor="let item of items" cdkDrag [cdkDragDisabled]="canDrag">...</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

What is the best way to assign a value to an option element for ordering purposes?

My select element is being populated with fruits from a database, using the following code: <select name="fruitsOption" id="fruitsOptionId" ngModel #fruitRef="ngModel"> <option *ngFor="let fruit of fruits">{{fruit}}</option> </selec ...

Tips for implementing a real-time search feature in Angular

I require assistance. I am attempting to perform a live search using the following code: when text is entered into an input, I want my targetListOptions array, which is used in a select dropdown, to update accordingly. The code runs without errors, but not ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...

Finding a solution for the network error encountered during the execution of XMLHttpRequest.send in the specified file path (...distfxcoreservermain.js:200

Having recently delved into Angular, I successfully completed the development of my angular web application. While using ng serve for production, everything ran smoothly. However, after incorporating angular universal and attempting npm run dev:ssr or np ...

Error: Typescript foreach loop encountering 'Expression yields void type'

Currently, I am working on setting up a cron job to monitor the completion of my tournaments and trigger some specific code upon completion. For reference, I came across this example: During deployment of my code, an error popped up as follows: ERROR: fu ...

What is the best way to retrieve property names that are not nullable from a type?

I am seeking to create a custom mapped conditional type in TypeScript that will allow me to extract property names from a type, while accounting for properties that can potentially have a value of null. For example: interface Person { name: string a ...

NextJS: Build error - TypeScript package not detected

I'm facing an issue while setting up my NextJS application in TypeScript on my hosting server. On my local machine, everything works fine when I run next build. However, on the server, I'm encountering this error: > next build It seems that T ...

The TypeScript error message indicates that a value typed as 'string | undefined' cannot be assigned to a type 'string'

In my TypeScript-based React application where I am utilizing material-ui for components, I am currently working on creating a wrapper for material-ui's input. Here is the code snippet: import FormControl, { FormControlProps } from "@material-ui/core ...

Using TypeScript to define data types for Supabase payloads

Currently, I'm working on integrating supabase into my ReactJS Typescript project. However, I'm unsure about the data type of the channel payload response and I aim to extract the eventType along with the new data. const handleInserts = () => ...

Error: The 'update' property cannot be found on the specified type

Starting a new AngularCli project and need to incorporate a Gauge chart. I've used the code from StackBlitz Angular Gauge Chart Example When I run ng serve --open, I encounter the following errors in the terminal: ERROR in src/app/gauge/gauge.comp ...

When imported, Node / JS instantly generates a new instance

Is there a way to instantiate a class without importing it first and using new afterward? Instead of var mainClass = require('../dist/main'); // has "class Main { ... }" var mainInstance = new mainClass(); I am looking for something like var ...

Filtering based on the boolean value of a checkbox in Angular

I'm struggling to implement a boolean filter for my search results, separating users with financial debt from those without. I need some guidance on how to achieve this. Data Filter @Pipe({ name: 'filter' }) export class FilterPipe implem ...

Angular 2, Release Candidate 5 - Dropdown form includes mysterious "phantom" choice

While working with Angular 2, RC 5, I have encountered a strange issue while building a form to create a new model object. The problem arises when there is an extra blank <option> appearing in the dropdown list after transpiling the code, even though ...

Steps for constructing an object literal with a property designated as the `keyof` type

Struggling to articulate my question, here is a simplified code snippet outlining what I aim to accomplish. class Example<T, TId extends keyof T> { public create(id: T[TId]): T { return { [TId]: id, // Encounter an error at this point. Ob ...

`Unresponsiveness in updating bound property after change in Angular2 child property`

Having trouble with my custom directive and ngOnChanges() not firing when changing a child property of the input. my.component.ts import {Component} from 'angular2/core'; import {MyDirective} from './my.directive'; @Component({ d ...

Switch up the item's background in the dropdown list within Kendo UI Angular

Looking for a solution to highlight text and change background color in a dropdown list based on certain conditions. I searched the official Kendo forum without success. Any guidance or suggestions on how to resolve this issue would be greatly appreciate ...

What is the best way to enhance a react-bootstrap component with TypeScript?

Currently, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f1d0a0e0c1b420d00001b1c1b1d0e1f2f5e415f415f420d0a1b0e415e5b">[email protected]</a> and delving into the development of a customized Button ...

Experiencing a type error within Redux in a React Native project utilizing TypeScript

I am currently working on implementing a feature to store the boolean value of whether a phone number is verified or not. Within my login component: await dispatch(setOTPVerified(data.is_phone_verified)); Action.tsx: export const OTP_VERIFIED = 'OTP ...

Exploring JSONPath in Cypress

I am currently working on extracting a JSON path for the specific HTML content with the language code DE Below is an example of the JSON data: { "name": "Name", "text": "", "html": "HTML content" ...

Encountered an HttpErrorResponse while trying to access the API endpoint

I am encountering an issue when trying to update and insert data with a single post request. Below is my API code: Here is the service code: This section includes the function calling code: Additionally, this is the model being used The API C# model c ...