Geek
Geek

Reputation: 3329

Angular 2 ngFor on the same tr element

Value of cList is :

code value1 value2
ABC  01     test1
DEF  02     test2
GHI  03     test3
JKL  04     test4
MNO  05     test5
PQR  06     test6
STU  07     test7
VWX  08     test8

my component.ts has the foll. arraylist. 1st 4 list is added to cList1 and 5-8 added to cList4.

cList: CaseInventorySummaryCustomDTO[] = [];
cList1: CaseInventorySummaryCustomDTO[] = [];
cList2: CaseInventorySummaryCustomDTO[] = [];

this.cList = this.data.cList;
for (let i = 0; i <= 3; i++) {                  
    this.cList1.push(this.cList[i]);
}
for (let i = 4; i < this.cList.length; i++) { 
    this.cList2.push(this.cList[i]);
}

my component.html is as follows:

<table>
<thead colspan="12">
    Subject Specialities
</thead>
<tr *ngFor="let i of cList1; let j of cList2">
    <td style="width: 4em">
       {{i.code}}
    </td>
    <td style="width: 3em">
        {{i.value1}}
    </td>
    <td colspan="2">
        {{i.value2}}
    </td>
    <td style="width: 4em">
        {{j.code}}
    </td>
    <td style="width: 3em">
        {{j.value1}}
    </td>
    <td colspan="2">
        {{j.value2}}
    </td>
</tr>
</table>

My expected output is

    Subject Specialities
ABC 01  test1   MNO 05  test5
DEF 02  test2   PQR 06  test6
GHI 03  test4   STU 07  test7
JKL 04  test4   VWX 08  test8

But what i see is,

    Subject Specialities
MNO 05  test5   MNO 05  test5
PQR 06  test6   PQR 06  test6
STU 07  test7   STU 07  test7
VWX 08  test8   VWX 08  test8

Does 2 ngFor not work on the same tr? or Am i wrong with the above code? Can someone please help.

Upvotes: 1

Views: 1320

Answers (1)

wangdev87
wangdev87

Reputation: 8751

You can't do the loop 2 arrays in one *ngFor. You can use the element <ng-container> for the second loop.

The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

<tr *ngFor="let i of cList1;">
  <ng-container *ngFor="let j of cList2">
    ...
  </ng-container>
</tr>

Solution for question

<tr *ngFor="let item of cList1; let i = index">
    <td style="width: 4em">
       {{i.code}}
    </td>
    <td style="width: 3em">
        {{i.value1}}
    </td>
    <td colspan="2">
        {{i.value2}}
    </td>
    <td style="width: 4em">
        {{cList2[i].code}}
    </td>
    <td style="width: 3em">
        {{cList2[i].value1}}
    </td>
    <td colspan="2">
        {{cList2[i].value2}}
    </td>
</tr>

Upvotes: 1

Related Questions