Accessing index in nested *ngFor loop

2.2k views Asked by At

This is a very peculiar problem for my project so if it is something dumb then please spare me.

I am building a dynamic table in Angular where each row is a word and Columns are the languages and each cell is the corresponding translation in that language.

So the problem is that I have to keep track of which table cell a user has clicked so that I can create or update the value of that cell.

The code is something like this:

    <tbody>

    <tr *ngFor="let data of data">

    <td contenteditable='true' (keyup.enter)="saveEntry($event)"  
    width="300px" height="40px" >{{data.key}}</td>

    <td *ngFor="let column of tableColumns;let j = index" 
      contenteditable='true'            
     (keyup.enter)="onRowClick($event, column.languageID,             
       data?.value[0]?.dictionaryEntryID)"                         

     (click)="TranslationClick($event,data.value[k].dictionaryID)">


   <ng-container *ngFor="let dataValue of data.value ;let k = index">

   <span *ngIf="column.languageID==dataValue.languageID">

   {{dataValue.translation}}</span>
    </span>
    <span *ngIf="column.languageID!=dataValue.languageID">
    </span>
     </ng-container>
     </td>
     </tr>
    </tbody>

Help needed : I need to get index k of the *ngFor in the ng-container in my TranslationClick method like this :

 (click)="TranslationClick($event,data.value[k].dictionaryID)

I know that the ng-container *ngFor loop is created after the first but Is there any way I can get the index k of that cell before hand.

Or is there any other better way to keep track of the individual cells of the table?

1

There are 1 answers

5
Günter Zöchbauer On

There is no way to access a template variable outside of the template where it is defined.

k can only be accessed within

   <ng-container *ngFor="let dataValue of data.value ;let k = index">

   <span *ngIf="column.languageID==dataValue.languageID">

   {{dataValue.translation}}</span>
    </span>
    <span *ngIf="column.languageID!=dataValue.languageID">
    </span>
   </ng-container>