Search code examples
angulartypescriptenumsswitch-statementangular17

Angular 17 @switch with Enum Constants


I want to use the new angular @switch statement to show different elements based on a Enum.

enum State {
  Loading,
  Loaded,
  Error
}

@Component({
...
})
export class MyComponent {
  state: State = State.Loading;
}

@switch (state) {
  @case (State.Loading) {
    <p>loading</p>
  }
  @case (State.Loaded) {
    <p>loaded</p>
  }
  @case (State.Error) {
    <p>error</p>
  }
}

The Problem it seems its not possible to reference the Enum Type inside html directly.

There are a few workarounds.

For example I could use the numbers instead of the Enum constants, but this would defeat the purpose of using a Enum in the first place.

@switch (state) {
  @case (0) {
    <p>loading</p>
  }
  @case (1) {
    <p>loaded</p>
  }
  @case (2) {
    <p>error</p>
  }
}

Or I could use a Composite type like this:

type State = 'Loading' | 'Loaded' | 'Error';

Is there a way to make this work with enums or do I need to switch to a different type?


Solution

  • Every symbol in a template must be accessible from the component.

    This means you need to expose the enum :

    @Component({
       ...
    })
    export class MyComponent {
      state: State = State.Loading;
      State = State; // State: typeof State = State
    }
    

    See this issue on that topic.