首页 > 解决方案 > Angular:如何使用 *ngFor 将指令绑定到元素

问题描述

<ng-container *ngFor='let column of columns'></ng-container>由于*ngFor. _ 我想仅将“粘性”属性(指令)应用于这些 ng-container 元素中的第一个。不给其他人。我怎样才能做到这一点?输出应如下所示:

<ng-container sticky></ng-container>
<ng-container></ng-container>
<ng-container></ng-container>
<ng-container></ng-container>
...

标签: javascriptangulartypescript

解决方案


ngFor指令有一个first变量,该变量仅在第一次迭代时为真。

ngIf一个else关键字,与模板变量一起可以有条件地呈现两个模板之一。

<ng-container *ngFor="let column of columns; first as isFirst">
    <ng-container *ngIf="isFirst; else notFirst" sticky></ng-container>
    <ng-template #notFirst></ng-template>
</ng-container>

推荐阅读