Posted under Angular
Permalink
Tags Angular, Tip
Sometimes you need an element to hang e.g. an *ngIf directive on, but you don’t want the element to appear in the markup.
In the following example, we end up with an extra unwanted <div> level just because we needed to hang the *ngIf somewhere (noting that it is not permissible to have the *ngIf on the same element as the *ngFor).
<div *ngFor="let place of places.rows">
<div *ngIf="place.doc.type == 'place'">
<span>{{place.doc.name}}, </span>
<span>{{place.doc.strapline}}</span>
</div>
</div>
Instead of a <div> we can use <ng-container>. This does not appear as an element in the markup (but does appear as a comment only) :-
<div *ngFor="let place of places.rows">
<ng-container *ngIf="place.doc.type == 'place'">
<span>{{place.doc.name}}, </span>
<span>{{place.doc.strapline}}</span>
</ng-container>
</div>
This is analagous to the <th:block> dummy element in Thymeleaf, which does exactly the same thing.
This StackOverflow post details this issue. This alternative post mentions the use of ng-if-start and ng-if-end, but notes that these are undocumented in Angular 2 so may not be fully supported.
For a related issue where nested loops are in use causing a similar problem, this post details the use of ng-repeat-start and ng-repeat-end as an alternative solution.
Note however that ng-repeat-start/ng-repeat-end only works for Angular 1.
Leave a Reply
You must be logged in to post a comment.