4

I have template with IF statement:

<li *ngIf="activity.entity_name == 'Project'" [activity-project-item]="activity"></li>
<li *ngIf="activity.entity_name == 'Tooling'" [activity-tooling-item]="activity"></li>
<li *ngIf="activity.entity_name != 'Project' && activity.entity_name != 'Tooling'" [activity-item]="activity"></li>

How to write this template with ngSwitch directive?

For example this template has parse error "Components on an embedded template":

<li [ngSwitch]="activity.entity_name">
    <template [ngSwitchCase]="'Project'" [activity-project-item]="activity"></template>
</li>

And this template has parse error "No provider for NgSwitch":

<template [ngSwitch]="activity.entity_name">
    <li [ngSwitchCase]="'Project'" [activity-project-item]="activity"></li>
</template>
Alexey Savchuk
  • 1,068
  • 6
  • 13
  • 26

2 Answers2

7

One possibility:

<li [ngSwitch]="activity.entity_name">
  <template [ngSwitchCase]="'Project'">Selected Project</template>
  <template [ngSwitchCase]="'Tooling'">Selected Tooling</template>
  <template ngSwitchDefault>Or else...</template>
</li>

Alternate syntax:

<div [ngSwitch]="activity.entity_name">
  <li *ngSwitchCase="'Project'">Selected Project</li>
  <li *ngSwitchCase="'Tooling'">Selected Tooling</li>
  <li *ngSwitchDefault>Or else...</li>
</div>

Take a look at the official docs and live demo.

Baumi
  • 1,745
  • 1
  • 17
  • 31
4

template

<li [ngSwitch]="activity.entity_name">
  <template [ngSwitchCase]="'Project'">Content here</template>
  <template [ngSwitchCase]="'Project2'">Other content here</template>
  <template ngSwitchDefault>Content if nothing matched</template>
</li>

Also make sure that the module that owns this component imports CommonModule. Otherwise, ngSwitch will not be recognized.

@NgModule({
    ...
    imports: [CommonModule...],
    declarations: [ThisComponent...],
    ...
})
export default class MyModule {}
BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
  • That's the correct answer. In Angular 8, this worked inside a component using [ngSwitchCase] not *ngSwitchCase. Check out xameeramir response to have a sense of what's happening: https://stackoverflow.com/questions/42456459/got-interpolation-where-expression-was-expected#42456529 – Konkret Dec 12 '19 at 19:50
  • From Angular: "NgSwitch itself is not a structural directive. It's an attribute directive that controls the behavior of the other two switch directives. That's why you write [ngSwitch], never *ngSwitch." https://angular.io/guide/structural-directives – Konkret Dec 13 '19 at 19:52