Introduction
Displaying content conditionally is one of the most common requirements in modern web applications. For example, you may want to show a login button only when the user is not authenticated, display an error message after a failed API request, or hide certain sections until data has finished loading.
Angular provides the *ngIf directive to handle these situations.
Angular 17 introduced the new built-in control flow syntax (@if), and Angular 20+ encourages developers to use @if for new projects.
What is the *ngIf Directive?
*ngIf is a structural directive that conditionally creates or removes HTML elements from the DOM.
If the condition evaluates to true, Angular creates and displays the element.
If the condition evaluates to false, Angular removes the element entirely.
Example:
Component:
isLoggedIn = true;
Template:
<h2 *ngIf="isLoggedIn">
Welcome User
</h2>
Output:
If isLoggedIn becomes false, Angular removes the <h2> element from the DOM.
Why Use *ngIf?
The *ngIf directive offers several benefits.
1. Conditional Rendering
Show or hide UI elements based on application state.
2. Better Performance
Elements that aren’t needed are removed from the DOM instead of remaining hidden.
3. Cleaner Templates
Instead of manually manipulating the DOM with JavaScript, Angular handles rendering automatically.
4. Improved User Experience
Display loading indicators, error messages, authentication screens, and dynamic content based on user actions.
Syntax of *ngIf
Basic syntax:
<div *ngIf="condition">
Content
</div>
Example:
showMessage = true;
<p *ngIf="showMessage">
Hello Angular!
</p>
When showMessage is true, Angular renders the paragraph.
How *ngIf Works
- It evaluates the condition.
- If the result is true, Angular creates the element.
- If the result is false, Angular removes the element.
- Angular continues monitoring the condition through change detection.
Basic Example
Component:
@Component({
selector: 'app-home',
standalone: true,
templateUrl: './home.component.html'
})
export class HomeComponent {
isVisible = true;
}
Template:
<div *ngIf="isVisible">
Angular Tutorial
</div>
Output:
Changing isVisible to false removes the <div> from the page.
Toggle Visibility
Component:
isVisible = true;
toggle() {
this.isVisible = !this.isVisible;
}
Template:
<button (click)="toggle()">
Toggle
</button>
<p *ngIf="isVisible">
This paragraph can be shown or hidden.
</p>
Each button click toggles the paragraph’s visibility.
Using *ngIf with else
You can display alternative content when the condition is false.
Component:
isLoggedIn = false;
Template:
<div *ngIf="isLoggedIn; else loginBlock">
Welcome Back!
</div>
<ng-template #loginBlock>
<p>Please log in.</p>
</ng-template>
Output:
When isLoggedIn becomes true, Angular displays:
Welcome Back!
Using *ngIf with then and else
Angular also supports separate then and else templates.
<div *ngIf="isAdmin; then adminTemplate; else userTemplate"></div>
<ng-template #adminTemplate>
<h2>Admin Dashboard</h2>
</ng-template>
<ng-template #userTemplate>
<h2>User Dashboard</h2>
</ng-template>
This approach is useful when templates become larger.
Using *ngIf with Logical Operators
You can combine multiple conditions.
Component:
isLoggedIn = true;
isAdmin = true;
Template:
<div *ngIf="isLoggedIn && isAdmin">
Admin Panel
</div>
The panel appears only when both conditions are true.
Using *ngIf with Comparison Operators
Component:
age = 20;
Template:
<p *ngIf="age >= 18">
Adult
</p>
Angular evaluates the comparison and displays the content only if the condition is satisfied.
Using *ngIf with Arrays
Component:
products = ['Laptop', 'Mouse'];
Template:
<p *ngIf="products.length > 0">
Products Available
</p>
If the array becomes empty, Angular removes the paragraph.
Using *ngIf with API Loading
A common real-world use case is displaying a loading message.
Component:
loading = true;
Template:
<div *ngIf="loading">
Loading...
</div>
After the API finishes:
loading = false;
Angular removes the loading indicator automatically.
Using *ngIf with Error Messages
Component:
hasError = true;
Template:
<div *ngIf="hasError">
Something went wrong.
</div>
Users only see the message when an error exists.
Using *ngIf with Forms
Component:
isSubmitted = false;
Template:
<form>
<!-- form fields -->
</form>
<p *ngIf="isSubmitted">
Form submitted successfully.
</p>
This provides immediate feedback after submission.
Using *ngIf with Async Data
Example:
<div *ngIf="user$ | async as user">
{{ user.name }}
</div>
Angular subscribes to the observable using the AsyncPipe and displays the content once data becomes available.
*ngIf vs Hidden Attribute
Developers often confuse *ngIf with the HTML hidden attribute.
Using hidden
<div [hidden]="true">
Angular
</div>
Result:
- Element remains in the DOM.
- Only hidden visually.
Using *ngIf
<div *ngIf="false">
Angular
</div>
Result:
- Element is completely removed from the DOM.
- Better for performance when content isn’t needed.
*ngIf vs @if (Angular 20+)
Angular 17 introduced the new built-in control flow syntax.
*ngIf
<div *ngIf="isLoggedIn">
Welcome
</div>
@if
@if (isLoggedIn) {
Welcome
}
Differences between *ngif vs @if
| Feature | ngIf | @if |
|---|---|---|
| Introduced | Structural directive | Structural directive |
| Requires * | Yes | No |
| Readability | Good | Better for complex conditions |
| Recommended for New Projects | Legacy support | Yes (Angular 20+) |
Recommendation: For new Angular 20+ applications, prefer @if. However, learning *ngIf remains essential because it is still widely used in existing Angular codebases.
Best Practices
1. Keep Conditions Simple
Good:
<div *ngIf="isLoggedIn">
Avoid long expressions with multiple nested conditions.
2. Move Complex Logic to Components
Instead of:
<div *ngIf="calculatePermission()">
Prefer:
canViewDashboard = true;
Then:
<div *ngIf="canViewDashboard">
3. Use else for Better UX
Instead of showing nothing when a condition is false, display helpful content.
Example:
- Loading…
- No Data Found
- Please Log In
4. Prefer @if in New Angular 20+ Projects
While *ngIf is still supported, Angular recommends using the newer built-in control flow syntax (@if) for newly written templates.
5. Avoid Deeply Nested *ngIf Blocks
Too many nested conditions make templates difficult to read.
Break large templates into smaller reusable components when appropriate.
Common Mistakes
1. Using hidden Instead of *ngIf
hidden only hides elements visually.
Use *ngIf when the element shouldn’t exist in the DOM.
<div *ngIf="user && user.role === 'admin' && isLoggedIn && hasPermission">
Move the logic into the component.
2. Forgetting the Asterisk
Incorrect:
<div ngIf="isVisible">
Correct:
<div *ngIf="isVisible">
3. Nesting Too Many Conditions
Large nested templates become difficult to maintain.
Use child components or the newer @if syntax for improved readability.
Advantages and Disadvantages
Advantages
- Easy to use
- Improves application performance
- Removes unnecessary DOM elements
- Keeps templates clean
- Supports else and then
- Works with observables and the AsyncPipe
- Integrates with Angular change detection
- Ideal for conditional rendering
Disadvantages
- Excessive nesting reduces readability
- Complex conditions should not be placed directly in templates
- Frequently toggled content may incur DOM creation and destruction costs
- @if is the preferred syntax for new Angular 20+ applications
When Should You Use *ngIf?
- You need to conditionally display content.
- Elements should be removed from the DOM when not needed.
- Rendering depends on API responses, authentication, or permissions.
- Youβre maintaining or enhancing existing Angular applications that already use *ngIf.
For new Angular 20+ projects, consider using the newer @if syntax where possible, as it offers improved readability and aligns with Angular’s modern template syntax.
Conclusion
The Angular *ngIf directive is one of the framework’s most important structural directives for conditional rendering. It allows developers to dynamically create or remove elements from the DOM based on Boolean expressions.
Angular 20+ encourages developers to adopt the newer @if control flow syntax for new applications.
Angular *ngIf Directive β Objective Questions (MCQs)
Q1. *ngIf is used for:
Q2. *ngIf removes elements from:
Q3. *ngIf works with:
Q4. *ngIf is a:
Q5. *ngIf uses: