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>
1
  • You need to make it a string "'true'" Commented Oct 17, 2017 at 10:30

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.