Elkin Elkin - 1 month ago 7
Javascript Question

How to get ordered indices inside two ngFor's?

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

product.component.html

<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]
</div>
</div>


product.component.ts

export class ProductComponent{

itens1=["A","B","C","D"];
itens2=["X","Y","Z"];
data=[1,2,3,4,5,6,7];

number=0;

getNumber(){
return this.number++;
}

}


These are the errors i get:

enter image description here

I hope to have explained my problem well.

Answer

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.

@Component({
    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)]}}">
  </div>
</div>`
})
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;
    }
}