0
0
Angularframework~20 mins

*ngSwitch for multiple conditions in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Using *ngSwitch for Multiple Conditions in Angular
📖 Scenario: You are building a simple Angular component that shows different messages based on a user's role. The roles can be 'admin', 'editor', or 'viewer'. You want to display a unique message for each role using Angular's *ngSwitch directive.
🎯 Goal: Create an Angular standalone component that uses *ngSwitch to display different messages for the roles 'admin', 'editor', and 'viewer'.
📋 What You'll Learn
Create a variable called userRole with the value 'editor'.
Create a variable called roles that holds the list ['admin', 'editor', 'viewer'].
Use *ngSwitch on userRole to show different messages for each role.
Add a default message for any role not in the list.
💡 Why This Matters
🌍 Real World
Many web apps need to show different content based on user roles or states. Using *ngSwitch helps manage these multiple conditions cleanly in Angular templates.
💼 Career
Understanding *ngSwitch is important for Angular developers to build dynamic user interfaces that respond to different data or user roles.
Progress0 / 4 steps
1
Set up the user role variable
Create a variable called userRole and set it to the string 'editor' inside the Angular component class.
Angular
Need a hint?

Use userRole = 'editor'; inside the class to create the variable.

2
Add the roles list variable
Add a variable called roles that holds the array ['admin', 'editor', 'viewer'] inside the Angular component class, below userRole.
Angular
Need a hint?

Use roles = ['admin', 'editor', 'viewer']; to create the list.

3
Use *ngSwitch to show messages for each role
In the component's template, use a div with *ngSwitch on userRole. Inside it, add *ngSwitchCase blocks for 'admin', 'editor', and 'viewer' that display the messages: 'Welcome Admin!', 'Hello Editor!', and 'Greetings Viewer!' respectively.
Angular
Need a hint?

Use *ngSwitch="userRole" on a container and add *ngSwitchCase="'admin'", *ngSwitchCase="'editor'", and *ngSwitchCase="'viewer'" inside it.

4
Add a default message with *ngSwitchDefault
Add a *ngSwitchDefault block inside the *ngSwitch container that shows the message 'Role not recognized.' for any role not matching the cases.
Angular
Need a hint?

Add <p *ngSwitchDefault>Role not recognized.</p> inside the *ngSwitch container.