Angular Drag and Drop Pass Additional Argument to Enter Predicate
Asked Answered
O

2

5

In my Angular Drag and Drop drop list, I want to pass an additional argument to the "[cdkDropListEnterPredicate]" function. By default it sends a CdkDrag and CdkDropList, but I have several drop lists so I only want one enter predicate function for them all. Here is my .html file:

<div class="players" [cdkDropListEnterPredicate]="filledPosition(drag, drop, '1')"
    cdkDropList #fwdLine1="cdkDropList" [cdkDropListData]="f1" 
    [cdkDropListConnectedTo]="[forwardPlayers]" 
    (cdkDropListDropped)="drop($event)">

    <div *ngFor="let fwd of f1" cdkDrag [cdkDragData]="fwd">
        <div class="player">
            <span>{{fwd.number}} {{fwd.name}} {{fwd.position}}</span>
        </div>
    </div>
</div>

And here is the function in the .ts file:

filledPosition = (item: CdkDrag<Skater>, list: CdkDropList, line) => {

    if (line == "1") checkLine = this.f1;

    console.log(item, list, line)

    if (checkLine.length >= 3) {
        return false;
    }

    return true;

}
Opiate answered 1/2, 2019 at 16:50 Comment(0)
D
15

Use a function which returns another function:

dropListEnterPredicate(id: number){
    return function(drag: CdkDrag, drop: CdkDropList) {
        return false;
    };
}

And call the outer function in the template:

[cdkDropListEnterPredicate]="dropListEnterPredicate('1')"

You can't call filledPosition(drag, drop, '1')" in the template. It will be immediately evaluated and send a boolean to the [cdkDropListEnterPredicate] binding instead of a function, which is what it wants.

Deciare answered 16/9, 2019 at 20:10 Comment(1)
For those who are interested; this process is commonly called "Currying".Quicklime
F
1

Each list can be assigned a unique ID with an input property https://material.angular.io/cdk/drag-drop/api. Perhaps assign a unique id to each list and then check for that ID in your predicate with a switch statement. I'm assuming each lists ID will then be accessible with list.id or some sort of getter function like list.id() inside of the predicate function.

Although I'm not sure exactly what you are building and it would seem more natural to have different functions for different lists. What are you dragging and dropping? When should it be droppable into a list and when not?

Fideism answered 1/2, 2019 at 17:13 Comment(1)
You set hockey lineups. There are four lines, each with a position (LW, C, RW). So I only want players whose position match to be allowed to drop in place.Opiate

© 2022 - 2024 — McMap. All rights reserved.