Using Enum Constants for @switch in Angular 17

I am looking to utilize the new angular @switch statement to display different elements based on an 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>
  }
}

It appears that referencing the Enum Type directly in html is not possible.

There are a few solutions to this issue.

For instance, I could use the numbers instead of the Enum constants, but this would go against the purpose of using an Enum in the first place.

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

Alternatively, I could opt for a Composite type like so:

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

Is there a way to make this work with enums or should I consider switching to a different type?

Answer №1

It is essential for every symbol in a template to be easily accessible from the component.

To achieve this, you must make sure to expose the enum:

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

For more information on this topic, check out this issue.

Answer №2

interface AppStatus {
  status: 'Loading' | 'Loaded' | 'Error';
}

@Component({
  // ...
})
export class MyComponent {
  appStatus: AppStatus = {status: 'Loading'};
}

When rendering the template, you can utilize the @switch statement with string literals:

@switch(appStatus.status)
{
  @case('Loading') {
    <p>loading</p>
  }
  @case('Loaded') {
    <p>loaded</p>
  }
  @case('Error') {
    <p>error</p>
  }
}

By employing a composite type with string literals, you can accurately depict different states without relying on enums directly within the template. This methodology enables you to achieve the desired functionality while staying within the confines of the Angular template syntax.

It's worth noting that leveraging string literals in this scenario offers a viable means of representing distinct states without resorting to using numerical values explicitly in the template. Despite requiring a slight adjustment in how states are represented, this approach effectively defines and utilizes various states within the template.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlimited Spiral of Angular NGXS Dispatch

I am encountering an infinite loop issue when this component is loading. Does anyone have any suggestions on how to resolve this? import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Sele ...

Installing Angular CLI

Upon installing the Angular CLI, I encountered the following warning: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\@angular\cli\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEP ...

What is the best way to test a function that returns a JSX element in a unit test

I created a function that takes in a parameter and returns a JSX.Element //title.tsx export const getTitle = (pageTitle: string) => { return <title> {pageTitle} </title>; } This is how I am currently testing it: describe('Title c ...

Is it possible to specify broad keys of a defined object in TypeScript using TypeScript's typing system?

const obj: {[key: string]: string} = {foo: 'x', bar: 'y'}; type ObjType = keyof typeof obj; Is there a way to restrict ObjType to only accept values "foo" or "bar" without changing the type of obj? ...

When making Angular GET requests, the response may return a single Object instead of an Array

When making a GET request to my API, the data is returned as Objects inside an Object instead of an Array of Objects. This makes it difficult for me to iterate through and print the data. I am puzzled by why this specific request is behaving differently c ...

Generate a nested array of objects by recursively looping through an array of objects

Imagine I have an array of objects structured like this: myArr = [ { "id": "aaa.bbb" }, { "id": "aaa.ccc" }, { "id": "111.222" }, { "id": "111.333" }, ] I aim t ...

Leveraging regular expressions for handling apostrophes

I need help with a function function convertToTitleCase(sentence: string) { return sentence.replace(/\b\w/s, word => word.toUpperCase()); } Current output: Men's apparel Desired output: Men's Apparel Can anyone assist me in achi ...

Ensuring that Vue3 Typescript app focuses on input element within Bootstrap modal upon opening

I am facing a challenge with setting the focus on a specific text input element within a modal dialog. I have tried various methods but none seem to achieve the desired outcome. Here is what I have attempted: Attempt 1: Using autofocus attribute. <inpu ...

Creating a grid UI in AngularJS using Typescript: utilizing functions as column values

I am working on an AngularJS app that includes the following UI grid: this.resultGrid = { enableRowSelection: true, enableRowHeaderSelection: false, enableHorizontalScrollbar: 0, enableSorting: true, columnDefs: [ { name: &apos ...

The React useEffect() hook causing an infinite re-render when trying to fetch all data regardless of

Recently, I've begun diving into React and utilizing the useEffect hook to fetch news and events from a database upon page load. However, when attempting to add a loading spinner, I encountered an unexpected infinite loop issue that has left me scratc ...

transferring data from service to component

Dealing with the challenge of passing a variable from a service (LibraryService) to a component located one level deeper in the directory structure (ReadingPaneComponent) has been quite troublesome for me. This predicament arose after successfully transfer ...

Guide to invoking an API in Next.js 13 by utilizing specific variables within a client component

I currently have a collection of products that are accessible on my website through a straightforward function within a server component. async function getData() { const res = await fetch(`${apiPath}`); const data = (await res.json()) as PackProps ...

Command to set up webpack configuration for watching changes in Angular 2 CLI: ng build --watch

Can I customize the configuration for my ng build --watch command in order to efficiently bundle and minify files on disk each time a modification is made? ...

Eliminate redundant elements

In my TypeScript code, I am working with an array of objects that looks like this: [ {target_col: "`qsze`", operation: "", isNew: false, operationNotCompiled: "", index: 25}, {target_col: "`qsf`", operation: "", isNew: false, operationNotCompiled: "", ...

What is the best way to create an "equals" method for an interface in mongodb?

export interface IHealthPlanCard { _id: string, statusId: string; } const cards: IHealthPlanCard[] = await healthPlanCardsCollection.find(...) cards.filter(card => card.statusId.equals(cardStatusId)) I encountered an issue in this scenario: An ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

It's possible that the "device.interfaces" variable has not been defined

I am currently working on creating a USB driver in TypeScript using the libusb library to adjust my keyboard lighting. However, I encountered an issue where I received a 'possibly undefined' error when trying to retrieve the interface number. The ...

Can an angular application be integrated with AWS Cognito for Windows authentication?

Looking for guidance on the main question in the header. I've tried researching but can't seem to find a clear tutorial or explanation. Any help would be greatly appreciated, thank you! ...

What are the reasons behind the compilation failure of the react-sortable-hoc basic example when using typescript?

Take a look at this sample code snippet extracted from the official react-sortable-hoc webpage. import React, {Component} from 'react'; ... // Code snippet goes here ... render(<SortableComponent/& ...

Encountering the error message 'array expected for services config' within my GitLab CI/CD pipeline

My goal is to set up a pipeline in GitLab for running WebdriverIO TypeScript and Cucumber framework tests. I am encountering an issue when trying to execute wdio.conf.ts in the pipeline, resulting in this error: GitLab pipeline error Below is a snippet of ...