Home > front end >  Angular: Using directives with *ngIf
Angular: Using directives with *ngIf

Time:12-11

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>

CodePudding user response:

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>

CodePudding user response:

Bind a function like this:

[cdkDropListConnectedTo]= "getDropList(i)"

Now inside your ts file, create the callback:

getDropList (i) {
 return i >= 2 ? [one, two] : [three, four];
}
  • Related