问题描述
我有一个简单的 ngFor
循环,它也跟踪当前的 index
.我想将该 index
值存储在一个属性中,以便我可以打印它.但我不知道这是如何工作的.
I have a simple ngFor
loop which also keeps track of the current index
. I want to store that index
value in an attribute so I can print it. But I can't figure out how this works.
我基本上有这个:
<ul *ngFor="#item of items; #i = index" data-index="#i">
<li>{{item}}</li>
</ul>
我想将#i
的值存储在属性data-index
中.我尝试了几种方法,但都没有奏效.
I want to store the value of #i
in the attribute data-index
. I tried several methods but none of them worked.
我在这里有一个演示:http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=预览
如何在 data-index
属性中存储 index
值?
How can I store the index
value in the data-index
attribute?
推荐答案
我会使用这种语法将索引值设置为 HTML 元素的属性:
I would use this syntax to set the index value into an attribute of the HTML element:
你必须使用 let
来声明值而不是 #
.
You have to use let
to declare the value rather than #
.
<ul>
<li *ngFor="let item of items; let i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
角度 = 1
<ul>
<li *ngFor="#item of items; #i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
这是更新的 plunkr:http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=预览.
Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.
这篇关于ngFor 将索引作为属性中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!