'How can I access the index outside *ngFor?

I want to use the variable i outside of my ngFor. What options are there to solve this problem?

Here is a small application example:

<ng-container *ngFor="let selection of selectionNumber; index as i;">
        <app-MyDropdown
          tabindex="{{i}}"
        ></app-MyDropdown
></ng-container>
<div>
    <button
      type="button"
      tabindex="{{i+1}}"
    >
      Button 1
    </button>
    <button
      type="button"
      color="primary"
      tabindex="i+2"
    >
      Button 2
    </button>
</div>

I want to use the i variable outside of the for loop to set the tab index. For this i should have the last value from the loop iteration.



Solution 1:[1]

It's not possible to use any value of *ngFor outside of whichever element you're running your ngFor loop in, (in your case that is ng-container). Which means you have to put your buttons inside of your ngContainer which will create button. But not sure if that's what you want to achieve.

Solution 2:[2]

You can not access any data of *ngFor from outside of the loop

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Can Geylan
Solution 2 Karan Chokshi