如何将 ngFor 循环的索引值传递给组件?
How to pass the index value of a ngFor loop into the component?
我的代码中有一个 ngFor 循环。
在这个 ngFor 循环中我有一个 div,点击这个 div 我想将索引值传递给类型脚本文件。
我是 Anglular 2 的新手,我们将不胜感激。
例如:
`<div *ngFor="let y of characters;let i = index">
<div (click)="passIndexValue()">
</div>
<div>`
<div *ngFor="let y of characters;let i = index">
<div (click)="passIndexValue(i)">
</div>
<div>`
passIndexValue(index){
console.log(index);//clicked index
}
您也可以像这样将值传递给组件(假设下面使用@Input)
<div *ngFor="let y of characters;let i = index">
<childComponent [index]="i">
</childComponent>
<div>`
然后在组件对象上取值:
@Input() index: number;
并直接在子组件的模板中使用:
<div id="mydivinstance_{{index}}"></div>
从而允许组件具有基于 *ngFor 循环的唯一 ID。
我的代码中有一个 ngFor 循环。 在这个 ngFor 循环中我有一个 div,点击这个 div 我想将索引值传递给类型脚本文件。
我是 Anglular 2 的新手,我们将不胜感激。
例如:
`<div *ngFor="let y of characters;let i = index">
<div (click)="passIndexValue()">
</div>
<div>`
<div *ngFor="let y of characters;let i = index">
<div (click)="passIndexValue(i)">
</div>
<div>`
passIndexValue(index){
console.log(index);//clicked index
}
您也可以像这样将值传递给组件(假设下面使用@Input)
<div *ngFor="let y of characters;let i = index">
<childComponent [index]="i">
</childComponent>
<div>`
然后在组件对象上取值:
@Input() index: number;
并直接在子组件的模板中使用:
<div id="mydivinstance_{{index}}"></div>
从而允许组件具有基于 *ngFor 循环的唯一 ID。