Elkin Elkin - 2 months ago 16
Javascript Question

How to get ordered indices inside two ngFor's?

This is my demo code where i explain my goal in comments:


<div *ngFor="let item of items1">
<div *ngFor="let item of items2">
<input type="text" value="{{data[getNumber()]}}"> //I want to get data[0] till data[6]


export class ProductComponent{



return this.number++;


These are the errors i get:

enter image description here

I hope to have explained my problem well.


The problem is that every time getNumber() is called, it returns a different value than before.

Every time Angular2 evaluates what to set value to during change detection, it has changed, it never settles. Angular2 regards this as an error. See this answer for a more complete explanation.

The following code works the way you intend. Note that getNumber is now idempotent, it gives the same result for the same input. The input is gotten from the loops using the syntax let i = index.

    selector: 'product',
    template: `
<div *ngFor="let item of items1; let i = index">
  <div *ngFor="let item of items2; let j = index">
      <input type="text" value="{{data[getNumber(i, j)]}}">
export class ProductComponent {
    items1 = ['A', 'B', 'C', 'D'];
    items2 = ['X', 'Y', 'Z'];
    data = [1, 2, 3, 4, 5, 6, 7];

    getNumber(i: number, j: number) {
        return i * this.items2.length + j;