Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

switch statement - Angular 2 ngSwitchCase, OR operator not working

I have multiple switch statement but for some case i need the common case. So, i am trying the

OR operator => ||

Example:

        <ng-container [ngSwitch]="options">
            <ng-container *ngSwitchCase="'a'">Code A</ng-container>
            <ng-container *ngSwitchCase="'b'">Code B</ng-container>
            <ng-container *ngSwitchCase="'c'">Code C</ng-container>
            <ng-container *ngSwitchCase="'d' || 'e' || 'f'">Common Code</ng-container>
            <ng-container *ngSwitchDefault>Code Default</ng-container>
        </ng-container>

Output:

if case = 'd' returns Common Code
else if case = 'e' and 'f' returns the Code Default 

Here the second last case consists of multiple cases, and now by default the case 'd' is only working and not working for case 'e' and 'f'.

I can't see any multiple case inside the ngSwitchCase docs:

https://angular.io/docs/ts/latest/api/common/index/NgSwitchCase-directive.html https://angular.io/docs/ts/latest/api/common/index/NgSwitch-directive.html

Doesn't Angular 2 supports the || operator in the ngSwitchCase?

question from:https://stackoverflow.com/questions/43775796/angular-2-ngswitchcase-or-operator-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you evaluate 'd' || 'e' || 'f' the result is 'd' and when options is not 'd', then it doesn't match. You can't use ngSwitchCase that way.

This would work:

    <ng-container [ngSwitch]="true">
        <ng-container *ngSwitchCase="options === 'a'">Code A</ng-container>
        <ng-container *ngSwitchCase="options === 'b'">Code B</ng-container>
        <ng-container *ngSwitchCase="options === 'c'">Code C</ng-container>
        <ng-container *ngSwitchCase="options === 'd' || options === 'e' || options === 'f'">Common Code</ng-container>
        <ng-container *ngSwitchDefault>Code Default</ng-container>
    </ng-container>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...