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