我有多个switch语句,但在某些情况下我需要常见的情况。所以,我正在尝试
OR operator => ||
示例:
<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>
输出:
if case = 'd' returns Common Code
else if case = 'e' and 'f' returns the Code Default
此处倒数第二个案例包含多个案例,现在默认情况下case 'd'
仅适用于case 'e' and 'f'
。
我在ngSwitchCase
文档中看不到任何多个案例:
https://angular.io/docs/ts/latest/api/common/index/NgSwitchCase-directive.html https://angular.io/docs/ts/latest/api/common/index/NgSwitch-directive.html
Angular 2不支持||
中的ngSwitchCase
运算符吗?
答案 0 :(得分:45)
如果您评估'd' || 'e' || 'f'
,结果为'd'
,而options
不是'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>
答案 1 :(得分:3)
我认为这种语法更好:
<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>
答案 2 :(得分:1)
感谢Bahador 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">