0

I am new to Angular. I am using ngSwitch in my program but every time I run the program *ngSwitchDefault executes rather than *ngSwitchCase. Here is the code:

<select [(ngModel)]="selectedControl" class="form-control">
    <option *ngFor="let inputControl of inputArray; let i=index" 
    [value]="inputControl">{{inputArray[i]}}</option>                                  
</select>
<span [ngSwitch]="selectedControl">
    <span *ngSwitchCase="text">
    <p>text is selected</p>              
    </span>
    <span *ngSwitchCase="radio">
    <p>radio is selected</p>
    </span>        
    <span *ngSwitchDefault>
    <p>Default value</p>
    </span>
</span>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
Waleed Shahzaib
  • 1,526
  • 2
  • 18
  • 34

3 Answers3

1

Wrap the *ngSwitchCase expressions into the '' to make them strings. The comparison will be used with ===, so it will compare string with string. In your case it is going to find a member with name radio or text and get their values, which are undefined.

<span [ngSwitch]="selectedControl">
    <span *ngSwitchCase="'text'">
    <!--                 ^----^ -->
    <p>text is selected</p>              
    </span>
    <span *ngSwitchCase="'radio'">
    <!--                 ^-----^ -->
    <p>radio is selected</p>
    </span>        
    <span *ngSwitchDefault>
    <p>Default value</p>
    </span>
</span>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

According to https://angular.io/api/common/NgSwitchCase ngSwitchCase expect expression not string. If you want to use hardcoded string replace *ngSwitchCase="text" with *ngSwitchCase="'text'"

zucker
  • 1,066
  • 12
  • 26
0

Unlike JavaScript, which uses strict equality, Angular uses loose equality. This means that the empty string, "" matches 0.

https://angular.io/api/common/NgSwitchCase

OliverE
  • 437
  • 5
  • 12
  • Answering with just a quote is usually a bit too brief. Please be so kind and add a sentence or two to relate the quote to the question. – B--rian Jul 25 '19 at 08:04