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
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
- Could you provide the response data that you want to loop. – Rohan Kangale Commented Jan 29, 2018 at 12:16
- Do you want data from car and data from bike alternatively? – Jayakrishnan Commented Jan 29, 2018 at 12:17
- No, it is a table with information about 2 different objects (I can not upload the JSON). I get the information perfectly but I do not know if it is possible to make two ngFor for the in the same row – bellotas Commented Jan 29, 2018 at 12:18
- what makes you think that you can iterate two arrays in the same ngFor? – Jota.Toledo Commented Jan 29, 2018 at 12:20
- angular doesn't support this kinda syntax... – radio_head Commented Jan 29, 2018 at 16:56
4 Answers
Reset to default 11You 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>
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>
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>
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>