Angular ngIf, ngFor & ngSwitch
Master Angular ngIf, ngFor, and ngSwitch with practical examples, Angular 17 control flow, trackBy, performance optimization, architecture diagrams, real-world examples, and interview questions.
Structural Directives are one of Angular's most important features. They allow developers to add, remove, repeat, or switch UI elements dynamically based on application data.
The three most commonly used structural directives are:
*ngIf– Conditionally display elements*ngFor– Repeat elements*ngSwitch– Display one view from multiple choices
Since Angular 17, Angular also introduced the new built-in control flow syntax:
@if@for@switch
Understanding both the traditional structural directives and the new control flow syntax is essential for Angular interviews and enterprise development.
Table of Contents
- What are Structural Directives?
- ngIf
- ngFor
- ngSwitch
- Angular 17 Control Flow
- trackBy Optimization
- Performance Best Practices
- Real-World Banking Example
- Top 10 Interview Questions
- Summary
What are Structural Directives?
Structural directives modify the DOM layout by adding, removing, or replacing elements.
Unlike attribute directives, structural directives change the structure of the page.
Examples:
- Show login page
- Display products
- Hide admin menu
- Render dashboard widgets
- Switch layouts
Structural Directive Architecture
flowchart TD
Component
Component --> ngIf
Component --> ngFor
Component --> ngSwitch
ngIf --> DOM
ngFor --> DOM
ngSwitch --> DOM
DOM --> Browser
Structural vs Attribute Directives
| Structural Directive | Attribute Directive |
|---|---|
| Changes DOM structure | Changes appearance/behavior |
| Adds or removes elements | Modifies existing elements |
Uses * syntax |
No * |
Example: *ngIf |
Example: ngClass |
What is ngIf?
*ngIf conditionally creates or removes elements from the DOM.
If the condition is true:
Element is created.
If false:
Element is removed from the DOM.
ngIf Flow
flowchart LR
Condition
Condition --> True
Condition --> False
True --> CreateDOM
False --> RemoveDOM
Basic ngIf Example
Component
isLoggedIn = true;
Template
<h2 *ngIf="isLoggedIn">
Welcome User
</h2>
Output
Welcome User
ngIf with else
<div *ngIf="isLoggedIn; else loginPage">
Dashboard
</div>
<ng-template #loginPage>
Please Login
</ng-template>
ngIf with then and else
<div *ngIf="isAdmin; then admin; else user">
</div>
<ng-template #admin>
Admin Dashboard
</ng-template>
<ng-template #user>
User Dashboard
</ng-template>
ngIf Architecture
sequenceDiagram
participant Component
participant ngIf
participant DOM
Component->>ngIf: isLoggedIn=true
ngIf->>DOM: Create Element
DOM-->>Browser: Render
What is ngFor?
*ngFor repeats HTML elements for every item in a collection.
Basic ngFor Example
Component
users = [
"Venu",
"John",
"David"
];
Template
<li
*ngFor="let user of users">
{{user}}
</li>
Output
Venu
John
David
ngFor Flow
flowchart LR
Array
Array --> ngFor
ngFor --> Item1
ngFor --> Item2
ngFor --> Item3
ngFor with Index
<li
*ngFor="let user of users;
let i = index">
{{i}}
{{user}}
</li>
Output
0 Venu
1 John
2 David
Useful ngFor Variables
| Variable | Description |
|---|---|
| index | Current index |
| first | First element |
| last | Last element |
| even | Even row |
| odd | Odd row |
| count | Total items (Angular 17 @for) |
Example
<div
*ngFor="let user of users;
let first = first">
{{first}}
</div>
trackBy Optimization
Without trackBy, Angular compares objects by identity and may recreate DOM elements unnecessarily when list references change.
<li
*ngFor="let user of users;
trackBy: trackById">
{{user.name}}
</li>
Component
trackById(index:number,user:User){
return user.id;
}
trackBy Architecture
flowchart TD
UpdatedArray
UpdatedArray --> trackBy
trackBy --> ExistingDOM
ExistingDOM --> ReuseNodes
ReuseNodes --> FasterRendering
What is ngSwitch?
*ngSwitch displays one view based on multiple possible values.
Basic Example
Component
status="ACTIVE";
Template
<div [ngSwitch]="status">
<div *ngSwitchCase="'ACTIVE'">
Active User
</div>
<div *ngSwitchCase="'BLOCKED'">
Blocked User
</div>
<div *ngSwitchDefault>
Unknown
</div>
</div>
ngSwitch Flow
flowchart TD
Status
Status --> Active
Status --> Blocked
Status --> Default
Active --> UI1
Blocked --> UI2
Default --> UI3
Angular 17 Control Flow
Angular introduced built-in control flow syntax.
@if
@if(isLoggedIn){
<h2>
Welcome
</h2>
}
@if ... @else
@if(isLoggedIn){
Dashboard
}
@else{
Login
}
@for
@for(user of users;
track user.id){
<div>
{{user.name}}
</div>
}
@empty
@for(user of users;
track user.id){
{{user.name}}
}
@empty{
No Users Found
}
@switch
@switch(status){
@case("ACTIVE"){
Active
}
@case("BLOCKED"){
Blocked
}
@default{
Unknown
}
}
Traditional vs Angular 17 Syntax
| Traditional | Angular 17 |
|---|---|
*ngIf |
@if |
*ngFor |
@for |
*ngSwitch |
@switch |
<ng-template> |
Built into syntax |
| More boilerplate | Cleaner templates |
Banking Dashboard Example
flowchart TD
Dashboard
Dashboard --> Accounts
Dashboard --> Transactions
Dashboard --> Loans
Dashboard --> Investments
Accounts --> ngFor
Transactions --> ngFor
Loans --> ngIf
Investments --> ngSwitch
Example
@if(accounts.length){
@for(account of accounts;
track account.id){
<app-account-card>
</app-account-card>
}
}
@else{
No Accounts
}
Performance Best Practices
| Practice | Benefit |
|---|---|
Use trackBy with *ngFor |
Reuse DOM elements |
Prefer @for in Angular 17+ |
Cleaner syntax and improved performance characteristics |
| Avoid expensive template methods | Faster change detection |
Use OnPush where appropriate |
Better rendering performance |
| Split large lists | Improved maintainability |
Common Mistakes
Missing trackBy
❌
*ngFor="let item of users"
For frequently changing large lists, omitting trackBy can lead to unnecessary DOM updates.
Nested ngIf
Too many nested conditions reduce readability.
Prefer:
computedValue
or separate components when appropriate.
Large Loops
Avoid rendering thousands of items at once.
Use:
- Virtual Scrolling
- Pagination
- Lazy Loading
ngIf vs Hidden
| ngIf | hidden |
|---|---|
| Removes element from DOM | Keeps element in DOM |
| Better for expensive UI | Better for quick visibility toggles |
| Frees resources | Element still exists |
Structural Directive Summary
| Directive | Purpose |
|---|---|
*ngIf |
Conditional rendering |
*ngFor |
Repeat items |
*ngSwitch |
Multiple conditions |
@if |
Angular 17 conditional |
@for |
Angular 17 iteration |
@switch |
Angular 17 switch |
Advantages
| Feature | Benefit |
|---|---|
| ngIf | Conditional rendering |
| ngFor | Dynamic lists |
| ngSwitch | Multiple conditions |
| @if | Cleaner templates |
| @for | Modern iteration |
| trackBy | Better performance |
Top 10 Angular ngIf, ngFor & ngSwitch Interview Questions
1. What is a Structural Directive?
Answer
A Structural Directive changes the DOM layout by adding, removing, or replacing elements.
Examples:
*ngIf*ngFor*ngSwitch
2. What is *ngIf?
Answer
*ngIf conditionally creates or removes elements from the DOM based on a Boolean expression.
3. What is the difference between *ngIf and hidden?
Answer
*ngIf |
hidden |
|---|---|
| Removes the element from the DOM | Keeps the element in the DOM |
| Frees resources | Only hides the element visually |
| Better for expensive components | Better for simple visibility toggles |
4. What is *ngFor?
Answer
*ngFor repeats an HTML template for every item in a collection such as an array or iterable.
5. What is trackBy?
Answer
trackBy helps Angular identify list items using a unique key, allowing it to reuse existing DOM elements instead of recreating them unnecessarily.
6. What is *ngSwitch?
Answer
*ngSwitch selects one template to display from multiple possible cases based on an expression.
7. What are Angular 17 control flow directives?
Answer
Angular 17 introduced built-in control flow syntax:
@if@for@switch@empty
These provide a cleaner alternative to traditional structural directives.
8. When should trackBy be used?
Answer
Use trackBy when rendering dynamic or frequently updated lists, especially large collections, to improve rendering performance.
9. Which is better: *ngFor or @for?
Answer
For new Angular 17+ applications, @for is generally recommended because it offers a cleaner syntax and integrates with the new control flow model. Existing applications can continue using *ngFor.
10. What are the best practices for Structural Directives?
Answer
- Use
trackByfor dynamic lists. - Prefer Angular 17 control flow in new projects.
- Keep conditions simple.
- Avoid deeply nested templates.
- Use pagination or virtual scrolling for large lists.
- Use
OnPushwhere appropriate.
Interview Cheat Sheet
| Topic | Remember |
|---|---|
| Conditional Rendering | *ngIf / @if |
| Iteration | *ngFor / @for |
| Multiple Cases | *ngSwitch / @switch |
| Empty List | @empty |
| Performance | trackBy |
| DOM Removal | *ngIf |
| Visibility Only | hidden |
| Index | index |
| First/Last | first, last |
| Angular 17 | Built-in Control Flow |
Summary
*ngIf, *ngFor, and *ngSwitch are the foundational structural directives in Angular for conditional rendering, list iteration, and multi-branch UI logic. Angular 17 enhances these capabilities with the new built-in control flow syntax (@if, @for, @switch, and @empty), resulting in cleaner and more expressive templates. Combined with trackBy, OnPush change detection, and efficient list rendering strategies, these features help developers build scalable and high-performance Angular applications.
Key Takeaways
- ✔
*ngIfconditionally creates or removes DOM elements. - ✔
*ngForrenders collections dynamically. - ✔
*ngSwitchdisplays one matching case. - ✔ Angular 17 introduces
@if,@for,@switch, and@empty. - ✔ Use
trackByfor large or frequently changing lists. - ✔ Keep template logic simple and readable.
- ✔ Use virtual scrolling or pagination for very large datasets.
Next Article
➡️ 25-ngClass-ngStyle-QA.md