Angular 2 ngSwitchCase, OR operator not working
I think this syntax is better:
<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>
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>
Thanks Bahador R, helped me create a pipe.
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;
}
}
use as
<ng-container [ngSwitch]="switchOption">
...
<div *ngSwitchCase="['somecase', 'anothercase'] | switchMultiCase:switchOption">