首页 > 解决方案 > 根据索引将元素添加到 ngfor dom

问题描述

我想基于索引渲染 DIV 元素,我不希望 DIV 渲染所有 ngfor“项目”。是否也可以在基于索引的 DIV 中拥有动态内容。感谢你的帮助。谢谢你。

<ul>
 <li *ngFor="let item of items; let i =index">
    <i (click)="add(i)">
    <div *ngIf="i">

    </div>
 </li>
</ul>

标签: javascriptangulartypescript

解决方案


要根据索引在 div 中包含动态内容,您只需使用示例中已经提供的 *ngIf :

<ul>
 <li *ngFor="let item of items; let i = index">
    <i (click)="add(i)">
    <div *ngIf="i === 0">
        Content for the first index
    </div>
 </li>
</ul>

div 只会出现在第一个索引的 DOM 中。

您还可以根据作为参数提供{{ }}的属性绑定值。i


推荐阅读