Angular 角度2开关箱,或操作员不工作

Angular 角度2开关箱,或操作员不工作,angular,switch-statement,ng-switch,or-operator,Angular,Switch Statement,Ng Switch,Or Operator,我有多个switch语句,但在某些情况下,我需要公共情况。所以,我正在尝试 或运算符=>| | 例如: <ng-container [ngSwitch]="options"> <ng-container *ngSwitchCase="'a'">Code A</ng-container> <ng-container *ngSwitchCase="'b'">Code B</ng-co

我有多个switch语句,但在某些情况下,我需要公共情况。所以,我正在尝试

或运算符=>| |

例如:

        <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>
这里最后一个案例由多个案例组成,现在默认情况下,
案例“d”
只对
案例“e”和“f”起作用,而不起作用

我在
ngSwitchCase
文档中看不到任何多个案例:


不支持
ngSwitchCase
中的
|
操作符如果您计算
'd'| |'e'| |'f'
结果是
'd'
,当
选项
不是
'd'
时,则不匹配。您不能那样使用
ngSwitchCase

这将有助于:

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

代码A
代码B
代码C
通用代码
代码默认值

我认为这种语法更好:

    <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'].includes(options) ? options : !options">Common Code</ng-container>
        <ng-container *ngSwitchDefault>Code Default</ng-container>
    </ng-container>

代码A
代码B
代码C
通用代码
代码默认值

谢谢巴哈多尔R,他帮助我创建了一个管道

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'switchMultiCase'
})
export class SwitchMultiCasePipe implements PipeTransform {

    transform(cases: any[], switchOption: any): any {
        return cases.includes(switchOption) ? switchOption : !switchOption;
    }

}
用作

<ng-container [ngSwitch]="switchOption">
...
<div *ngSwitchCase="['somecase', 'anothercase'] | switchMultiCase:switchOption">

...

Wow!你是角神,我不认为开关应该有真实的状态谢谢你的帮助。我挠头好几个小时了。谢谢,不用客气。很高兴听到它解决了您的问题:)工作!关键点:[ngSwitch]=“true”将允许评估所有“SwitchCase条件”标记。我认为在这种情况下使用*ngIf比破解ngSwitch更好。代码越少越好readability@Mihail我还认为,直到我意识到违约案件更加复杂
<ng-container [ngSwitch]="switchOption">
...
<div *ngSwitchCase="['somecase', 'anothercase'] | switchMultiCase:switchOption">