This post will guide you on how to use ngIf with ngFor structural directive in Angular.
ngFor and ngIf should not be used in the same element together. It has to be used in separate HTML elements like below,
<div *ngFor="let video of videos">
<div *ngIf="video.genre=='music'">
{{video.title}}
</div>
</div>
When using ngIf and ngFor structural directives use ng-container element for ngIf.
Instead of using div, li, or p element for ngIf use ng-container element. ng-container element won't be added to the DOM.
Div with CSS * Selector
div * {
margin-top: 10px;
}
Consider ngIf is used with div and if a CSS style is applied globally to div using CSS * selector, then it will cause non desirable outcome in design. To resolve this use ng-container for ngIf. ng-container element won't interfere with the CSS style.
For example, a margin-top of 10px is applied globally for a div element. The above example will apply a margin-top of 10px for the first div element and the second element will leave a 10 pixel to its top. This is the best example to explain this issue. I faced this issue during real-time application development. Using ng-container fixes the unnecessary element rendering in the DOM issue.
<div *ngFor="let video of videos">
<ng-container *ngIf="video.genre=='music'">
{{video.title}}
</ng-container>
</div>
Suppose we want to check the length of the videos list before rendering the inner div and again we want to check the video genre after iterating the videos ng-container will be much useful and won't add any unwanted div element to the DOM.
<ng-container *ngIf=="videos.length">
<div *ngFor="let video of videos">
<ng-container *ngIf="video.genre=='music'">
{{video.title}}
</ng-container>
</div>
</ng-container>
When your application grows and the application has a lot of if statements, using ng-container will eliminate the extra div elements.