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>
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>