在点击事件上传递ngfor索引

时间:2019-08-09 16:27:32

标签: html angular

所以我有这个ngfor,我想将它的索引传递给click事件的方法(selectGateway)。但它始终只是传递零。

但是,当我使用插值显示索引时,它会显示所有元素的所有正确索引。

我尝试了“让i = index”和“与i相同的索引”。

使用Angular 5.我在做什么错了?

<div id="depcity{{i}}" *ngFor="let item of filteredGatewayList; let i = index" (click)="selectGateway(i)">
  <span class="fa fa-map-marker"></span>  <span>{{i}}{{item.gateway_name}}</span>
</div>

selectGateway(ind:any){

alert("ind = "+ind);

this.filteredDestinationList = [];
if(ind == -1){
    this.gatewayInput = this.filteredGatewayList[this.selectedGatewayIndex]['gateway_name'];
    this.gatewayListHidden = true;
    this.selectedGatewayIndex = ind;
    this.filteredDestinationList = this.filteredGatewayList[this.selectedGatewayIndex];
    this.destinationInput = '';
}else{
    this.gatewayInput = this.filteredGatewayList[ind]['gateway_name'];
    this.gatewayListHidden = true;
    this.selectedGatewayIndex = ind;
    this.filteredDestinationList = this.filteredGatewayList[this.selectedGatewayIndex];
    this.destinationInput = '';
}
this.hideClearDepCity = false;

}

2 个答案:

答案 0 :(得分:1)

通过索引的片段:

<div *ngFor='let item of items;let i = index' (click)='getIndex(i)'>

WORKING DEMO

答案 1 :(得分:0)

好了。问题是我也在其他地方使用了i变量。