簡體   English   中英

Angular:將指令與 *ngIf 結合使用

[英]Angular: Using directives with *ngIf

是否可以說如果i >= 2那么[cdkDropListConnectedTo]="[one, two]" ,否則[cdkDropListConnectedTo]="[three, four]"

*ngIf對我不起作用。 我還搜索了“Angular ngif 指令”。 然而,我要找的答案並沒有出來。

<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>

根據您的問題,您正在根據條件分配值。 您可以通過以下方式實現:

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

*ngIf用於根據條件是否渲染元素。 因此*ngIf不適合您的情況。

除非您嘗試使用*ngIf with else模板作為:

<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>

像這樣綁定 function:

[cdkDropListConnectedTo]= "getDropList(i)"

現在在你的 ts 文件中,創建回調:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM