Reputation: 2480
I want to implement ngSwitch
in my code like this:
<div [ngSwitch]="accessLevel">
<div class="customer" *ngSwitchCase="ENABLED">
This is customer data
</div>
<div *ngSwitchDefault>
this is default
</div>
<div class="customer-blurr" *ngSwitchCase="DISABLED">
This is disabled Customer Data
</div>
</div>
In my case accessLevel
is undefined and I am expecting this is default
but it is showing:
This is customer data.
This is disabled Customer Data.
As I read from the official docs, if nothing matches it should go to default case. Am I missing something?
Upvotes: 1
Views: 12031
Reputation: 13558
Change your HTML as below :
<div [ngSwitch]="accessLevel">
<div class="customer" *ngSwitchCase="'ENABLED'">
This is customer data
</div>
<div *ngSwitchDefault>
this is default
</div>
<div class="customer-blurr" *ngSwitchCase="'DISABLED'">
This is disabled Customer Data
</div>
</div>
Note: you need to add single quotes inside the double quotes so Angular knows it is a string literal rather than a variable.
Upvotes: 6
Reputation: 122061
Note that the value of the *ngSwitchCase
directive must be the expression to match, not the value. In your case, you're presumably wanting to compare to the string 'ENABLED'
, rather than some field with that name, therefore it should be e.g.:
<div class="customer" *ngSwitchCase="'ENABLED'">
<!-- ^ note quotes -->
You are seeing both the ENABLED
and DISABLED
cases because neither of those names are defined, so you're actually matching undefined == undefined
, which evaluates truthy. The default is therefore not shown, but both of the other cases are.
Alternatively, you could define some constants or an enum to compare to, rather than passing around strings, which would improve the semantics of your code.
Upvotes: 2