As many frontend developers know, the structural directive *ngIf is one of the most essential features of the Angular framework. However many developers continue to make mistakes in this regard. Today we will discuss some of the most common pitfalls of the *ngIf structural directive.
1. Using div instead of ng-container
Unless you absolutely need an HTML element with styles and classes, it’s best to use ng-container instead. The ng-container comes in handy when you simply need to check a condition because it does not render an HTML element. While it’s not crucial to do this, it can certainly help keep your code clean.
2. Forgetting the question mark (?) operator
While not directly related to *ngIf itself, this mistake often occurs when using it. Omitting the question mark operator in an object chain can easily lead to errors. For example, in the following code snippet:
<div *ngIf="object.item.subitem">
we see an object chain inside the *ngIf. If an object or member is undefined (in this case, object or item), then the content in your will not be displayed, even though you are checking the condition.*ngIf
Here is a better solution:
<div *ngIf="object?.item?.subitem">
3. Not using *ngIf at all
Omitting *ngIf entirely can lead to you wondering where all your content is, because you are not checking if your data exists in the first place!
4. Using the wrong syntax
The version update to Angular 20 has brought many big changes to the framework, including the new syntax of the *ngIf directive. If you are used to seeing this in earlier versions:
<ng-container *ngIf="welcome">
<p>Welcome!</p>
</ng-container>
Then you need update your code to the new syntax for Angular 20:
@if (welcome) {
<p>Welcome!</p>
}
Conclusion
Hopefully this post can help both newcomers just starting out with the *ngIf structural directive in Angular as well as the veterans who wish to improve their skills. Happy Coding!
