Recently I was using ngSwitch in my code, and found that no case block was showing for me. I tried to find any logical error I had. But I could not find any error, and no error was showing on the console as well.
When I went to the https://angular.io/api/common/NgSwitchCase and read it, nothing helped for me. Below is the syntax:
<container-element [ngSwitch]="switch_expression">
<some-element *ngSwitchCase="match_expression_1">...</some-element>
...
<some-element *ngSwitchDefault>...</some-element>
</container-element>
Then one of my colleagues helped me to find the error. Below are the examples of that error and solution.
Code Which was behaving differently:
<div [ngSwitch]="switchWord">
<div *ngSwitchCase="D1">Div 1 without quotes</div>
<div *ngSwitchCase="D2">Div 2 without quotes</div>
<div *ngSwitchCase="D3">Div 3 without quotes</div>
</div>
Solution:
<div [ngSwitch]="switchWord">
<div *ngSwitchCase="'D1'">Div with quotes 1</div>
<div *ngSwitchCase="'D2'">Div with quotes 2</div>
<div *ngSwitchCase="'D3'">Div with quotes 3</div>
</div>
Explanation:
First, I thought it is a syntax error, but if it was a syntax error, it should have shown on the console.
That means this is not the syntax error, and this is not at all an error. Only I had used ngSwitchCase wrongly.
If you look at both codes above, you will find a minor difference of single quotes only.
ngSwitchCase takes and matches the expressions. Whatever you write in the (‘ ’) in the single quotes, angular considers as a string constant. Whatever you write in "" will be evaluated then compared to the switchWord.
[Note: If you are passing a variable and you have assigned a value in that variable, use that variable in the ngSwitchCase without single quotes]
*ngSwitchCase="'D2'" -> Constant value; switchWord must be the value 'D2'
*ngSwitchCase="'D3' + 'S'" ->Evaluation two constant values added; evaluates to 'D3S'; switchWord must be the value 'D3S'
*ngSwitchCase="'3 + 7'" ->Constant values; switchWord must be the value '3 + 7'
*ngSwitchCase="D2" -> Evaluation of Variable; switchWord must have the same value as variable D2
Hope This is helpful, Thank you
ZimBaroo's GitHub Code