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

Time:11-01

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]"
        
        *ngIf="isFirstRound()"
        cdkDropListOrientation="horizontal"
        (cdkDropListDropped)="drop($event)">
        <div *ngFor="let card of weisenList">
            <img  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]"
        
        cdkDropListOrientation="horizontal"
        (cdkDropListDropped)="drop($event)">
        <div *ngFor="let card of playerThreeHandList">
            <img  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.

CodePudding user response:

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.

CodePudding user response:

You can try by using @ViewChild

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

component

@ViewChild("weisenElement",{read:CdkDroplist}) //or whatever that is exporeted as `cdkDropList`
public weisen:CdkDroplist; change any to the proper type

just keep in mind that wesien is nullable.

  • Related