Search code examples
javascriptangulartypescriptngfor

ngFor : using 2 indexes in ng for changes the value in wrong way


I have to print check boxes. which is working fine, but I cant initialize id and name of it using ngfor correctly. It is giving me wrong value

lets say 2 arrays (or n arrays from database)

animal = 'dog', 'cat'

vehicle = 'bus', 'plane', 'train'

so If I use 2 ngFor it should be like (i, j is index)

i = 0 , j=0 > i = 0, j = 1

then next row should be

i = 1, j = 0 > i = 1, j = 1 > i=1, j = 2

Here is my code :

<form>
  <div class="form-group row" *ngFor="let firstColumn of mapMenusFirstColumn; index as i">
    <label class="col-4">{{firstColumn}}</label>
    <div class="col-8">
      <div class="custom-control custom-checkbox custom-control-inline" *ngFor="let secondColumn of this.getSecondColumn(this.mapMenu,firstColumn); index as j">
        <input name= {{i}}  id={{i+'_'+j}} type="checkbox" class="custom-control-input" value={{secondColumn}}>
        <label for={{i+'_'+j}} class="custom-control-label">{{secondColumn}}</label>
      </div>
    </div>
  </div>
</form>

So name should be 0 -> when id 0_0

name should be 0 -> when id 0_1

name should be 1 -> when id 1_0

name should be 1 -> when id 1_1

name should be 1 -> when id 1_2

[ I am not showing actual data because it is so huge (n rows) , just screenshot given ]

When I use id and name both i :

enter image description here

But When I use i as name (beacause for 3/4 check items, checkbox name should be same) and j as id :

enter image description here

It seems like i is in j's position . I can assure you : I tried reversing i to j , but didn't work.

I would also like to know about different implementations


Solution

  • After just (blindly) trying random things, this worked

    Only edit is -

    1. I have to use trackby
    2. To write a string, I am using double quote " " for both id and name

    [ I don't know why It worked, Because, it was still a string under interpolation {{ }} . BTW, I would really appreciate your explanation ]

    <form>
      <div class="form-group row" *ngFor="let firstColumn of mapMenusFirstColumn; index as i;">
        <label class="col-4">{{firstColumn}}</label>
        <div class="col-8">
          <div class="custom-control custom-checkbox custom-control-inline"
            *ngFor="let secondColumn of this.getSecondColumn(this.mapMenu,firstColumn); index as j;">
            <input name="checkbox{{i}}" id="checkbox{{i+'_'+j}}" type="checkbox" class="custom-control-input"
              value={{secondColumn}}>
            <label for="checkbox{{i+'_'+j}}" class="custom-control-label">{{secondColumn}}</label>
          </div>
        </div>
      </div>
    </form>
    

    in my .ts

      trackByFn(i: number) {
        return i;
      }