Reputation: 9
NgIf and NgFor in same element to reduce elements in the DOM
Situation I have:
<li *ngFor="let item of array; let i = index">
<content *ngIf="i < someVar"></content>
</li>
Situation I want:
<li *ngFor="let item of array; let i = index" *ngIf="i < someVar">
<content></content>
</li>
I want to have the ngIf
and ngFor
tag in the same element, because I don't want the DOM to be filled with 'list item' tags.
Is there a way to do something like this, or do I just have to live with it?
Upvotes: 0
Views: 194
Reputation: 38094
For this purpose use ng-container
:
<ng-conainer *ngIf="someCondition">
<li *ngFor="let item of array; let i = index" >
<content></content>
</li>
</ng-container>
OR:
<li *ngFor="let item of array; let i = index" >
<content *ngIf="someCondition"></content>
</li>
Upvotes: 3
Reputation: 3432
You can't use multiple structural directives (like ngIf, ngFor, ngSwitch) in a single element. Use ng-container
instead.
<li *ngFor="let item of array; let i = index">
<ng-container *ngIf="i < someVar">
<content ></content>
</ng-container>
</li>
ng-container doesn't get rendered at runtime, so your html will look like:
<li> <content> </content> </li>
<li> <content> </content> </li>
<li> <content> </content> </li>
<li> <content> </content> </li>...
The reason why Angular doesn't allow to add more than one structural directive is given by the Angular doc:
Someday you'll want to repeat a block of HTML but only when a particular condition is true. You'll try to put both an *ngFor and an *ngIf on the same host element. Angular won't let you. You may apply only one structural directive to an element.
The reason is simplicity. Structural directives can do complex things with the host element and its descendents. When two directives lay claim to the same host element, which one takes precedence? Which should go first, the NgIf or the NgFor? Can the NgIf cancel the effect of the NgFor? If so (and it seems like it should be so), how should Angular generalize the ability to cancel for other structural directives?
There are no easy answers to these questions. Prohibiting multiple structural directives makes them moot. There's an easy solution for this use case: put the *ngIf on a container element that wraps the *ngFor element. One or both elements can be an ng-container so you don't have to introduce extra levels of HTML.
https://angular.io/guide/structural-directives
Upvotes: 2