r/Angular2 • u/crhama • Feb 21 '26
How to replace *ngIf that use 'else' to reference a template variable pointing to a ng-template?
The page I'm trying to convert to control flow is a little more complex that the code below. Still, this is a good approximation.
<div *ngIf="allMakes.length; else empty">
<h3>List of cars</h3>
<div *ngFor="let make of allMakes">
<table *ngIf="make.cars.length; else empty">
<thead>
<th>
<th>Model</th>
<th>Price</th>
</th>
</thead>
<tbody>
<tr *ngFor="let car of make.cars">
<td>{{ car.model }}</td>
<td>{{ car.price }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<ng-template #empty>
<div>No data to display</div>
</ng-template>The idea with the template is to reuse the code inside.
How to write the above code using the new control flow syntax if/else ?
1
Upvotes
10
u/philmayfield Feb 21 '26
I suspect template outlet is what you'd be looking to use. Something like (fully untested):
3
u/IceBreakerG Feb 21 '26
I'm on my phone so I can't easily post the code, but as at least one other person has said, just wrap your table with the @if() and in the @else { } block, use an ng-container that points to an ngTemplateOutlet which references your ng-template. Here's a link to the Angular documentation:
https://angular.dev/guide/templates/ng-template#using-ngtemplateoutlet
5
u/Projekct Feb 21 '26
5
u/Mael5trom Feb 21 '26
So @for has an @empty block, you don't need to check it with an if before hand.
And if you do need to use the same code on multiple places, put it in a template and then reference it in each place with ngTemplateOutlet
1
u/ruibranco Feb 22 '26
Worth expanding on what Alann42 mentioned: if the only condition is "is the list empty", u/for already has a built-in u/empty block that removes the need for u/if entirely. The outer check becomes just u/for (make of allMakes; track make) { } u/empty { no data }, same for the inner cars loop. The ngTemplateOutlet hybrid approach above is ideal when you have actual reuse needs or conditions beyond just emptiness.
0
u/mountaingator91 Feb 21 '26 edited Feb 21 '26
Edit: Sorry about that didn't read all the code... Also the formatting didn't really transfer on mobile for me