*ngSwitch Directive in Angular
The *ngSwitch
directive in Angular allows you to conditionally include or exclude a set of elements based on a switch expression. This tutorial covers the basics of the *ngSwitch
directive and how to use it effectively in your Angular applications.
What is the *ngSwitch Directive?
The *ngSwitch
directive is used to display one element tree from a set of possible element trees based on the value of a switch expression. It is composed of three main directives:
ngSwitch
: The directive used to define the switch expression.ngSwitchCase
: The directive used to match a specific case.ngSwitchDefault
: The directive used to define a default case when no other case matches.
Basic Syntax of *ngSwitch
Here is a basic example of using the *ngSwitch
directive:
<div [ngSwitch]="color">
<div *ngSwitchCase="'red'">Red</div>
<div *ngSwitchCase="'green'">Green</div>
<div *ngSwitchCase="'blue'">Blue</div>
<div *ngSwitchDefault>Default color</div>
</div>
export class AppComponent {
color = 'red';
}
Using ngSwitchCase
The ngSwitchCase
directive is used to define a case in the switch expression. Each ngSwitchCase
directive compares its expression against the switch expression and displays the element if there is a match.
Using ngSwitchDefault
The ngSwitchDefault
directive is used to define a default case when none of the ngSwitchCase
directives match the switch expression.
Complex Examples
You can use *ngSwitch
with more complex data structures and nested elements:
<div [ngSwitch]="selectedItem.type">
<div *ngSwitchCase="'book'">
<h3>Book Details</h3>
<p>Title: {{ selectedItem.title }}</p>
<p>Author: {{ selectedItem.author }}</p>
</div>
<div *ngSwitchCase="'movie'">
<h3>Movie Details</h3>
<p>Title: {{ selectedItem.title }}</p>
<p>Director: {{ selectedItem.director }}</p>
</div>
<div *ngSwitchDefault>
<p>Select an item to see details</p>
</div>
</div>
export class AppComponent {
selectedItem = { type: 'book', title: '1984', author: 'George Orwell' };
}
Key Points
- The
*ngSwitch
directive is used to conditionally include or exclude a set of elements based on a switch expression. - The
ngSwitchCase
directive defines a specific case to match against the switch expression. - The
ngSwitchDefault
directive defines a default case when no other case matches. - Use
*ngSwitch
with complex data structures and nested elements to create more dynamic templates.
Conclusion
The *ngSwitch
directive is a powerful tool for conditionally displaying elements based on the value of an expression. By understanding and using the *ngSwitch
directive effectively, you can create more dynamic and flexible Angular applications. Happy coding!