In this tutorial we are going to resolve the issue of using *ngFor and *ngIf on same element. so, in angular ngIf and ngFor is a structural directives, and we can not use two structural directive on same element.ngIf is used for to make conditional logic and ngFor is used for to repeat the element.
You can also read about What is directives and types of directive in angular? and what is structural directives in angular.
Why we can’t use two structural directive on same element in angular 12?
In angularjs (angularjs is first version of angular) we can use both on same element but not in angular 2 because Angular unable to decide which one to use first for example if we are using ngIf and ngFor together.
<div *ngIf='place.id>10' *ngFor="let place of places">
<p>{{place}}<p>
</div>
In the above example, if angular try to execute first ngIf then place is undefined for it.
So, above code will throw below exception
Error
Can’t have multiple template bindings on one element. Use only one attribute prefixed with *
So, Now come to the main point.
To use ngFor and ngIf on element we can create parent child strategy see below example:
<div *ngIf='place.id>10'>
<div *ngFor="let place of places">
<p>{{place}}<p>
</div>
</div>
But in above example it will create a extra div so to eliminate this we can use ng-container
<ng-container *ngIf='place.id>10'>
<div *ngFor="let place of places">
<p>{{place}}<p>
</div>
</ng-container>