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

Discussão em 'Angular' iniciado por Peter T., Janeiro 30, 2025.

  1. Peter T.

    Peter T. Guest

    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.

    Continue reading...

Compartilhe esta Página