angularangular-materialangular-cdkangular-cdk-drag-drop

Why cdkDropList element cannot be hidden conditionally using *ngIf? Is there a workaround for that?


I have multiple cdkDropLists, and I drag and drop items from one to the other. However, I want one of them to be hidden in certain conditions, defined by a function in my Angular component's .ts file.

The HTML code snippet on how I want to do it is presented below:

<div
        cdkDropList
        #weisen="cdkDropList"
        [cdkDropListData]="weisenList"
        [cdkDropListConnectedTo]="[playerThreeHand]"
        class="horizontal weisen"
        *ngIf="isFirstRound()"
        cdkDropListOrientation="horizontal"
        (cdkDropListDropped)="drop($event)">
        <div *ngFor="let card of weisenList">
            <img class="horizontal_card" src="assets/french_cards/{{card.cardID}}.svg" cdkDrag>
        </div>
    </div>

However, this cdkDropList is referenced by another cdkDropList:

<div
        cdkDropList
        #playerThreeHand="cdkDropList"
        [cdkDropListData]="playerThreeHandList"
        [cdkDropListConnectedTo]="[cardsOnTable, weisen]"
        class="horizontal bottom"
        cdkDropListOrientation="horizontal"
        (cdkDropListDropped)="drop($event)">
        <div *ngFor="let card of playerThreeHandList">
            <img class="horizontal_card" src="assets/french_cards/{{card.cardID}}.svg" cdkDrag>
        </div>
    </div>

Without the ngIf, the code compiles; but when ngIf attribute is added, the following error message pops:

Error: src/app/game/game.component.html:83:50 - error TS2551: Property 'weisen' does not exist on type 'GameComponent'.

83         [cdkDropListConnectedTo]="[cardsOnTable, weisen]"
                                                    ~~~~~~

  src/app/game/game.component.ts:9:16
    9   templateUrl: './game.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component GameComponent.

Solution

  • The problem is that your first component with the ngIf does not exist when the condition isFirstRound() is not met, so it cannot be referenced.

    Instead of *ngIf="isFirstRound()" you can try [hidden]="!isFirstRound()" so that the element still exists, but is only hidden in later rounds.