How do you conditionally display or hide elements in modern Angular , similar to the older ngShow/ngHide directives?Question For - Junior Level Developer
Question
How do you conditionally display or hide elements in modern Angular , similar to the older ngShow/ngHide directives?Question For – Junior Level Developer
Brief Answer
In modern Angular, we primarily use two directives for conditional display, replacing the older AngularJS ngShow/ngHide directives, which are now deprecated:
-
*ngIf: Controls Element Existence (Structural Directive)- How it works: This is a structural directive that completely adds or removes the element and its children from the Document Object Model (DOM). Think of it as “create or destroy.”
- Performance: It offers better performance for complex components or when elements are hidden for extended periods, as Angular doesn’t run change detection or manage the state of elements removed from the DOM.
- When to use: Ideal for complex components, sections with heavy data bindings, or when rendering depends on a fundamental state change (e.g., user logged in/out, displaying a detailed report).
- Example:
<app-user-profile *ngIf="isLoggedIn"></app-user-profile>
-
[hidden]: Toggles Visibility (Attribute Directive)- How it works: This is an attribute directive that toggles an element’s visibility by adding or removing the HTML
hiddenattribute, which typically appliesdisplay: none;via CSS. The element remains in the DOM. Think of it as “show or hide.” - Performance: While faster for initial rendering as the element is always present, Angular still performs change detection on the element even when it’s hidden.
- When to use: Best for simpler elements, small UI elements, or when content is frequently toggled (e.g., loading spinners, error messages, toggle buttons) where the overhead of DOM creation/destruction would be greater.
- Example:
<div [hidden]="!isLoading">Loading...</div>
- How it works: This is an attribute directive that toggles an element’s visibility by adding or removing the HTML
Key Takeaway: Choose *ngIf for performance-critical scenarios involving DOM manipulation (removing/adding), especially with complex content. Use [hidden] for simpler, visual toggles or frequent changes where the element’s DOM presence is acceptable.
Super Brief Answer
In modern Angular, we use *ngIf and [hidden]. The older ngShow/ngHide are deprecated.
*ngIf: A structural directive that removes/adds the element from/to the DOM. Use for complex components or performance-critical hiding.[hidden]: An attribute directive that hides the element via CSS (display: none;) while it remains in the DOM. Use for simple, frequently toggled elements.
*ngIf impacts the DOM structure, while [hidden] only affects visibility.
Detailed Answer
In modern Angular, the primary directives for conditionally displaying or hiding elements are *ngIf and the [hidden] attribute. These replace the older AngularJS ngShow and ngHide directives, offering distinct approaches to DOM manipulation and performance implications.
Key Concepts
- Structural Directives: Directives that change the DOM layout by adding or removing DOM elements.
*ngIfis a structural directive. - Attribute Directives: Directives that change the appearance or behavior of an element, component, or another directive.
[hidden]is an attribute directive. - Template Syntax: Angular’s way of extending HTML with special syntax for data binding, directives, and more.
- DOM Manipulation: The process of changing the structure, style, or content of the Document Object Model.
Understanding Angular’s Conditional Display Directives
1. *ngIf: Controlling Element Existence in the DOM
*ngIf is a structural directive that controls whether an element and its children are added to or removed from the DOM. If the expression bound to *ngIf evaluates to false, the element and its entire subtree are completely removed from the DOM and are not rendered at all. Conversely, if the expression is true, the element is added to the DOM.
Think of *ngIf as “create or destroy.”
Explanation:
*ngIf completely removes the element and its children from the DOM, leading to better performance, especially for complex components. Angular doesn’t need to manage these hidden elements, preventing unnecessary change detection and updates. This makes *ngIf ideal when conditional rendering is based on substantial changes in data or logic, where the hidden element doesn’t need to consume any resources.
2. [hidden]: Toggling Visibility via CSS
[hidden] is an attribute directive that toggles an element’s visibility through the HTML hidden attribute. When the hidden attribute is present (e.g., [hidden]="true"), the browser applies display: none; via CSS, making the element invisible. The key difference is that the element remains in the DOM but simply isn’t displayed.
Think of [hidden] as “show or hide.”
Explanation:
[hidden] simply toggles visibility. The element remains in the DOM, which can be less performant than *ngIf for very complex components or frequent toggling, as Angular still needs to manage its internal state and bindings. However, it’s a good choice for simple visibility changes and offers slightly faster initial render performance because the element is always present in the DOM, just hidden.
3. ngShow / ngHide: Deprecated in Modern Angular
While functional in older AngularJS versions, ngShow and ngHide are not part of modern Angular (Angular 2+). These directives used CSS to manipulate the display property (e.g., display: block; or display: none;).
Explanation:
ngShow and ngHide are considered legacy. Modern Angular favors *ngIf and [hidden] due to their cleaner approach, better integration with Angular’s change detection mechanism, and the distinct performance benefits offered by DOM manipulation versus simple CSS toggling. Demonstrating knowledge of their deprecated status shows awareness of current Angular best practices.
Performance: Key Difference Based on DOM Manipulation
The core distinction in performance between *ngIf and [hidden] lies in how they interact with the DOM:
-
*ngIfPerformance:*ngIfis generally better for complex elements or components with many data bindings or child components, especially when hidden for extended periods or toggled infrequently. Because it removes the element entirely from the DOM, Angular doesn’t need to perform any change detection or updates on it when it’s hidden, leading to significant performance gains. There might be a slight overhead for the initial creation and destruction, but the gains when hidden typically outweigh this for complex elements. -
[hidden]Performance:[hidden]is sufficient for simpler cases, like a small loading spinner or a simple message. It has a faster initial render because the element is always in the DOM. However, if the hidden element is complex or frequently toggled, Angular still needs to run change detection on it, even when it’s not visible. This can lead to decreased performance compared to*ngIfin such scenarios.
When to Use Which: Scenarios and Best Practices
When choosing between *ngIf and [hidden], consider the complexity of the element and the frequency of toggling:
Scenario 1: Complex Components or Significant Data Changes (Use *ngIf)
Imagine a complex user profile component that is shown conditionally based on user login status. This component might contain numerous data bindings, child components, and intricate logic. In this case, *ngIf would be the preferred choice because removing the entire component from the DOM when the user is logged out significantly improves performance by preventing unnecessary change detection and updates. This also applies to elements that are conditionally rendered based on substantial data state changes where the element’s presence reflects a fundamentally different state.
<!-- Using *ngIf to conditionally render a complex user profile -->
<app-user-profile *ngIf="isLoggedIn"></app-user-profile>
<div *ngIf="showDetailedReport">
<!-- Complex report component with charts and tables -->
<app-detailed-report></app-detailed-report>
</div>
Scenario 2: Simple Elements or Frequent Toggles (Use [hidden])
Consider a simple “loading” indicator (like a spinner) that is shown while data is being fetched, or a basic error message that appears briefly. These elements typically have minimal overhead and are toggled frequently. Using [hidden] is perfectly acceptable here as the performance impact of simply toggling their visibility via CSS is negligible. It also avoids the overhead of creating/destroying the element repeatedly.
<!-- Using [hidden] to toggle visibility of a simple loading spinner -->
<div [hidden]="!isLoading">
<img src="spinner.gif" alt="Loading...">
<p>Loading data...</p>
</div>
<!-- Using [hidden] for a simple error message -->
<p [hidden]="!errorMessage" style="color: red;">{{ errorMessage }}</p>
Code Samples
Here are basic examples demonstrating the usage of *ngIf and [hidden]:
<!-- app.component.html -->
<!-- Using *ngIf to conditionally render the element based on 'showContent' -->
<div *ngIf="showContent">
<h3>Content displayed by *ngIf</h3>
<p>This element is added to the DOM only when 'showContent' is true.</p>
</div>
<!-- Using [hidden] to toggle visibility based on 'showContent' -->
<div [hidden]="!showContent">
<h3>Content displayed by [hidden]</h3>
<p>This element is always in the DOM, but its visibility is toggled.</p>
</div>
<button (click)="toggleContent()">Toggle Content</button>
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
showContent: boolean = true;
toggleContent(): void {
this.showContent = !this.showContent;
}
}
Conclusion
For modern Angular development, master the use of *ngIf for DOM manipulation (adding/removing elements) and [hidden] for CSS-based visibility toggling. Understanding their distinct behaviors and performance implications is crucial for writing efficient and maintainable Angular applications. Always prefer these modern directives over the deprecated ngShow/ngHide.

