Bird
0
0

You need to show different greetings for user roles: 'admin', 'editor', 'guest', and a fallback message for any other role. Which Angular template correctly implements this using *ngSwitch?

hard📝 component behavior Q8 of 15
Angular - Directives
You need to show different greetings for user roles: 'admin', 'editor', 'guest', and a fallback message for any other role. Which Angular template correctly implements this using *ngSwitch?
A<pre><div [ngSwitch]="userRole"> <div *ngSwitchCase="admin">Welcome Admin</div> <div *ngSwitchCase="editor">Hello Editor</div> <div *ngSwitchCase="guest">Hi Guest</div> <div *ngSwitchCase>Welcome User</div> </div></pre>
B<pre><div [ngSwitch]="userRole"> <div *ngSwitchCase="'admin'">Welcome Admin</div> <div *ngSwitchCase="'editor'">Hello Editor</div> <div *ngSwitchCase="'guest'">Hi Guest</div> <div *ngSwitchDefault>Welcome User</div> </div></pre>
C<pre><div *ngSwitch="userRole"> <div *ngSwitchCase="'admin'">Welcome Admin</div> <div *ngSwitchCase="'editor'">Hello Editor</div> <div *ngSwitchCase="'guest'">Hi Guest</div> <div *ngSwitchCase="default">Welcome User</div> </div></pre>
D<pre><div [ngSwitch]="userRole"> <div *ngSwitchCase="'admin'">Welcome Admin</div> <div *ngSwitchCase="'editor'">Hello Editor</div> <div *ngSwitchCase="'guest'">Hi Guest</div> <div *ngSwitchCase="'*'">Welcome User</div> </div></pre>
Step-by-Step Solution
Solution:
  1. Step 1: Check syntax for *ngSwitch and cases

    The [ngSwitch] directive binds the switch expression; *ngSwitchCase values must be quoted strings for string matching.
  2. Step 2: Identify default case

    The default case must use *ngSwitchDefault, not *ngSwitchCase without value or with 'default' string.
  3. Step 3: Evaluate options

    <div [ngSwitch]="userRole">
      <div *ngSwitchCase="'admin'">Welcome Admin</div>
      <div *ngSwitchCase="'editor'">Hello Editor</div>
      <div *ngSwitchCase="'guest'">Hi Guest</div>
      <div *ngSwitchDefault>Welcome User</div>
    </div>
    correctly uses quoted strings for cases and *ngSwitchDefault for fallback.
  4. Final Answer:

    <div [ngSwitch]="userRole">
      <div *ngSwitchCase="'admin'">Welcome Admin</div>
      <div *ngSwitchCase="'editor'">Hello Editor</div>
      <div *ngSwitchCase="'guest'">Hi Guest</div>
      <div *ngSwitchDefault>Welcome User</div>
    </div>
    is the correct Angular template.
  5. Quick Check:

    Default case uses *ngSwitchDefault and string values are quoted [OK]
Quick Trick: Use *ngSwitchDefault for fallback and quote string cases [OK]
Common Mistakes:
  • Not quoting string values in *ngSwitchCase
  • Using *ngSwitchCase without value for default
  • Using 'default' string instead of *ngSwitchDefault

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes