Table displays only the last Repeat Loop value

Asked

Viewed 58 times

0

I made a table that searches 100 items from within my API, now I need to number the rows in that table. For that, I created a variable number called columns and made a FOR:

colunas: number;


linhasTeste(){
      for(let i = 1 ; i < 101; i++){
        this.colunas  = i;
        console.log('linhas:', this.colunas);
      }
  }

The result of my console.log returning a counter from 1 to 100 that was expected, but in my column rows, only the last result of the loop appears.

<tbody>
  <tr *ngFor="let pokemon of pokemons[0]">
    <td>
      {{colunas}}
    </td>
    <td>
      {{pokemon.name}}
    </td>
    <td>
      {{pokemon.url}}
    </td>
  </tr>
  <tr>
</tbody>

How can I display the numbers in ascending order in my table from 1 to 100? Thank you!

inserir a descrição da imagem aqui

  • 2

    You don’t need that, the ngFor already has an index to be used in HTML, would just do ngFor="let pokemon of pokemons[0]"; let idx = index and use idx in place of columns.

1 answer

5


I took a look at the Angular documentation: https://angular.io/api/common/NgForOf#local-variables

And I saw that in every noose ngFor the angular provides some variables for you, and between them, it provides the index, which is what you need. Then html could look like this:

<tbody>
  <tr *ngFor="let pokemon of pokemons[0]">
    <td>
      {{index + 1}}
    </td>
    <td>
      {{pokemon.name}}
    </td>
    <td>
      {{pokemon.url}}
    </td>
  </tr>
  <tr>
</tbody>

Or if you want to use the name colunas instead of index.

<tbody>
  <tr *ngFor="let pokemon of pokemons[0]; index as colunas">
    <td>
      {{colunas + 1}}
    </td>
    <td>
      {{pokemon.name}}
    </td>
    <td>
      {{pokemon.url}}
    </td>
  </tr>
  <tr>
</tbody>

UPDATING: It was necessary to put the + 1 because the value of index starts at zero, not 1.

  • 1

    good would only put index+1 pq starts at 0

  • truth... I’ll correct there

Browser other questions tagged

You are not signed in. Login or sign up in order to post.