Search code examples
angularangular-directiveangular-ng-if

Angular: Using directives with *ngIf


Is it somehow possible to say if i >= 2 then [cdkDropListConnectedTo]="[one, two]", otherwise [cdkDropListConnectedTo]="[three, four]"?

*ngIf didn't work for me. I also searched for "Angular ngif directives". However, the answers I was looking for did not come out.

<div *ngFor="let task of this.tasks; let i = index">
    <div>
        <div
            cdkDropList
            id="task-container-{{i}}"
            #ref{{i}}="cdkDropList"
            [cdkDropListData]="task.getDropListData()"
            [cdkDropListConnectedTo]= "[]"
            (cdkDropListDropped)="drop($event)">
            <div>
                <p>{{task.getHeadline()}}</p>
            </div>
        </div>
    </div>
</div>

Solution

  • From your question, you are assigning the value based on the condition. You can achieve with:

    [cdkDropListConnectedTo]="i >= 2 ? [one, two] : [three, four]"
    

    *ngIf is used to render the element or not by the condition. Hence *ngIf is not suitable in your scenario.

    Unless you are attempting with *ngIf with else template as:

    <div *ngIf="i > 2; else elseTemplate"
      cdkDropList
      id="task-container-{{i}}"
      #ref{{i}}="cdkDropList"
      [cdkDropListData]="task.getDropListData()"  
      [cdkDropListConnectedTo]="[one, two]"
      (cdkDropListDropped)="drop($event)">
      ...
    </div>
    
    <ng-template #elseTemplate
      cdkDropList
      id="task-container-{{i}}"
      #ref{{i}}="cdkDropList"
      [cdkDropListData]="task.getDropListData()"
      [cdkDropListConnectedTo]="[three, four]"
      (cdkDropListDropped)="drop($event)">
      ...
    </ng-template>