bellotas
bellotas

Reputation: 2461

Double *ngFor in a table - Angular 2

I need to create a table based in two loops. I have tried the following:

<tbody *ngIf="testCases">
  <tr class="pointer" *ngFor="let car of cars; let bike of bikes">
    <td class="center">{{car?.id}}</td>
     <td class="center">{{bike?.id}}</td>
  </tr>
</tbody>

I know the I get the data because I have tried it in typescript with console.log but when I display it in HTML I print null for bike

Upvotes: 2

Views: 10370

Answers (4)

Sumeet Kale
Sumeet Kale

Reputation: 365

In your typescript code you can do this:

vehicles = (<any[]>cars).concat(<any>[bikes]);

And then in your view you can bind it easily like:

<tr class="pointer" *ngFor="let vehicle of vehicles">
  <td *ngIf="vehicle.vehicleType === 'car'" class="center">{{vehicle.id}} is car</td>
  <td *ngIf="vehicle.vehicleType === 'bike'" class="center">{{vehicle.id}} is bike</td>
</tr>

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657496

You can use <ng-container>. It is a helper element that allows to use *ngFor, *ngIf, or other structural directives but doesn't actually create HTML content.

<ng-container *ngFor="let car of cars">
  <tr class="pointer" *ngFor="let bike of bikes"> 
    <td>{{car.id}} {{bike.id}}</td>
  </tr>
</ng-container>

Upvotes: 11

Vivek Doshi
Vivek Doshi

Reputation: 58573

If both have same no of records , you can do it like

<tr class="pointer" *ngFor="let car of cars; let i = index;">
    <td class="center">{{cars[i]?.id}}</td> // or <td class="center">{{car?.id}}</td>
    <td class="center">{{bikes[i]?.id}}</td>
</tr>

Upvotes: 3

Sajeetharan
Sajeetharan

Reputation: 222592

You cannot use on the same line, try it as separate rows

<tbody *ngIf="testCases">
  <tr class="pointer" *ngFor="let car of cars ">
    <td class="center">{{car?.id}}</td>
   </tr>
  <tr class="pointer" *ngFor="let bike of bikes">
    <td class="center">{{bike?.id}}</td>
  </tr>
</tbody>

EDIT

if you want on the same row use index which will hold the array value

<tr class="pointer" *ngFor="let car of cars; let x = index;">
    <td class="center">{{cars[x]?.id}}</td>
    <td class="center">{{bikes[x]?.id}}</td>
</tr>

Upvotes: 0

Related Questions