Vikram R Vikram R - 21 days ago 12
Javascript Question

how to slice td limit by 2 in table angular

I have a

carsList
array having 5 values. i try
slice
2 by 2

<table>
<tr *ngFor="#item of carsList | slice:0:2; #i = index">
<td>{{i}}. {{item}}</td>
</tr>
</table>


above code split 2 values only. I want slice 2 by 2.

Example

0 1
2 3
4 5


Code:

https://plnkr.co/edit/BZnaSIldgO3Dmwao1mo6?p=preview

kindly help me . where is my mistake.

Answer Source

The slice pipe results an array with 2 elements and ngFor would iterate over the elements in the resulted array, that doesn't provide the expected result.

To achieve the result either you need to convert the array structure or do something like this with an additional ngIf with nested ngFor.

<table>
  <ng-container *ngFor="#item of carsList; #i = index">
    <tr *ngIf="i % 2 === 0">
      <td *ngFor="#item1 of carsList|slice:i:i + 2; #i1 = index" class="car-title">{{i1}}. {{item1}}</td>
    </tr>
  </ng-container>
</table>

or by removing nested ngFor and simply creating 2 td manually.

<table>
  <ng-container *ngFor="#item of carsList; #i = index">
    <tr *ngIf="i %2 === 0">
      <td>{{i}}. {{item}}</td>
      <td>{{ i + 1 }}. {{carsList[i + 1]}}</td>
    </tr>
  </ng-container>
</table>

FYI : Where ng-container can be used to group element which doesn't put in the DOM tree.

Updated plunker link.