Search code examples
htmlangulartypescriptswitch-statementangular-control-flow

Using Angular's @switch() that shares a template for several @case?


Seven years ago, this question has been asked already for Angular's old ngSwitch/ *ngSwitchCase syntax. Updating our templates to the nice new syntax, I step across the same question again: What is the best way to avoid duplicated parts in situations where several cases share the same UI?

The Angular docs state that @switch does not support fallthrough (which I regard as a good choice to avoid all errors with missing breaks). But as far as I see, they didn't add something to give a list of options to a single @case?

So the only way is to use <ng-template>? E.g.

  @switch (type) {
    @case ('type1') { ... }
    <ng-template #shared>Some UI shared for several cases</ng-template>
    @case ('type2') { <ng-container *ngTemplateOutlet="shared"/> }
    @case ('type3') { <ng-container *ngTemplateOutlet="shared"/> }
    @case ('type4') { ... }

Or, use @default and @if inside? Not sure which way would be better to understand and maintain.


Solution

  • It might lead to cleaner code using the switch statement for actual distinguished cases, and therefore it is better to map the switch variable accordingly in ts file (e.g. using some computed signal).