Tips for creating an Angular component that can receive a single value from a choice of two different lists

My angular component requires a value that belongs to one of two lists.

For example:

@Input()
public type!: enumA | enumB;

However, this setup becomes problematic when the enums share values or are linked together in a way I find undesirable. I would prefer to avoid using string enums as well. What is the most effective way to clearly distinguish between receiving enumA.Foo or enumB.Foo?

In this illustration, enums are utilized but I am open to alternative solutions.

Answer №1

Unfortunately, this is just how enums function. They are essentially a way to assign names to numerical values for easier understanding. Ultimately, they boil down to numbers, making it difficult to determine the original array based solely on a number like 3.

Below is an example in TypeScript, or you can view it on TS Playground

 enum enumA {
    One = 1,
    Two = 2,
    Three = 3
 }

  enum enumB {
    One = 1,
    Two = 2,
    Three = 3
 }
 
 var x: enumA | enumB = enumB.Three;

 console.log(typeof x, x);

 console.log(typeof enumB, enumB)

This will output:

"number",  3 

"object",  {
  "1": "One",
  "2": "Two",
  "3": "Three",
  "One": 1,
  "Two": 2,
  "Three": 3
}

Enums do not provide enough information to trace back to their source as desired.

If you must use enums, one workaround is to include a second property to store the entire enum and its value separately:

TS Playground link

 enum enumA {
    One = 1,
    Two = 2,
    Three = 3
 }

  enum enumB {
    One = 1,
    Two = 2,
    Three = 3
 }

 interface IGenericEnum {
   [s: number]: string
 }
 
function test<T = IGenericEnum>(list: T, val: keyof T){
   console.log(list, val);
}

test(enumA, "One"); 

While not perfect, this approach provides a bit more information by separating enum values into individual fields. It remains strongly typed, preventing errors like attempting test(enumA, "Foo").

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

The View does not get updated by Angular's *ngFor directive

When I modify the Array of servers from outside the class declaration, the View/HTML component does not update accordingly. However, when I perform the same modification from inside the class, it works fine. Both functions successfully update the servers A ...

Issue encountered when attempting to access disk JSON data: 404 error code detected

I am attempting to retrieve JSON data from the disk using a service: import { Product } from './../models/Product'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from &apo ...

Facing a problem with querying interfaces and types in TypeScript

My goal is to pass a variable to an RTK Query API service that uses a typescript interface: const device_id: unique symbol = Symbol(props.id); const { data: device, isFetching, isLoading, } = useGetAssetsByIdQuery(device_id, { pollingInterv ...

Node OOM Error in Webpack Dev Server due to Material UI Typescript Integration

Currently in the process of upgrading from material-ui v0.19.1 to v1.0.0-beta.20. Initially, everything seems fine as Webpack dev server compiles successfully upon boot. However, upon making the first change, Node throws an Out of Memory error with the fol ...

Mastering the art of utilizing Angular Material's custom-palette colors for maximum impact. Unle

I have implemented a custom material-color palette where I defined the primary and accent palettes with specific shades as shown below: $my-app-primary: mat-palette($md-lightprimary ,500,900,A700 ); $my-app-accent: mat-palette($md-lightaccent, 500,900 ...

Issue with Angular Reactive form: Checkbox checked property not binding correctly when the page initially loads

Looking to achieve Two-way data binding of Checkbox in Angular Reactive forms. After checking the checkbox, I am updating the 'isdateChkd' variable and storing it in the state. Despite the variable being set to TRUE, the checkbox does not get aut ...

NGXS Alert: Unable to resolve parameters for TranslationEditorState: (?)

I'm currently implementing NGXS for state management within my Angular 9 application. I've encountered a specific issue where any attempt at dependency injection in one of the state classes results in an error message stating "Error: Can't r ...

Encountering a Nuxt error where properties of null are being attempted to be read, specifically the 'addEventListener' property. As a result, both the default

Currently, I am utilizing nuxt.js along with vuesax as my UI framework. I made particular adjustments to my default.vue file located in the /layouts directory by incorporating a basic navbar template example from vuesax. Subsequently, I employed @nuxtjs/ ...

Dealing with challenges in integrating ngx-masonry with Angular 14

I am currently working with Angular 14 framework and the ngx-masonry library (https://www.npmjs.com/package/ngx-masonry/v/14.0.1). However, I am facing some issues where it is not functioning correctly. I would appreciate any assistance or guidance on how ...

Having trouble compiling Angular CLI version 8.3.21 with the command ng serve

Upon trying to compile my first Angular app, I encountered an error when running ng serve: ERROR in ./src/styles.css (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded! ...

Navigating through object keys in YupTrying to iterate through the keys of an

Looking for the best approach to iterate through dynamically created forms using Yup? In my application, users can add an infinite number of small forms that only ask for a client's name (required), surname, and age. I have used Formik to create them ...

Creating a dynamic return statement in typescript: A step-by-step guide

I am looking to dynamically set a return value to a variable based on values retrieved from an API. The current function in question uses static values: this.markDisabled = (date: NgbDate) => { return (this.calendar.getWeekday(date) !== 5 && ...

Troubleshooting Angular: Issues with Table Data Display and Source Map Error

I'm currently tackling a challenge in my Angular application where I am unable to display data in a table. When I fetch data from a service and assign it to a "rows" variable within the ngOnInit of my component, everything seems to be working fine bas ...

Creating HTML content in TypeScript with NativeScript using document.write()

Essentially, I am looking to create a set number of labels at various row and column positions depending on the user's input. However, I have been unable to find any resources that explain how to write to the .component.html file from the .component.t ...

Modify a property within an object and then emit the entire object as an Observable

I currently have an object structured in the following way: const obj: SomeType = { images: {imageOrder1: imageLink, imageOrder2: imageLink}, imageOrder: [imageOrder1, imageOrder2] } The task at hand is to update each image within the obj.images array ...

Preventing Firebase duplicates leads to the error of not being able to read the property 'apps'

Struggling to incorporate Firebase into a TypeScript/NextJS project, I have encountered difficulties. Despite successfully importing and initializing the app: import * as firebase from "firebase/app"; import { collection, getDocs } from "fir ...

An error occurred because the property 'coSearchCriteria' is being read from an undefined source in Angular Karma/Jasmine

I am attempting to test an Angular component using Karma and Jasmine. However, I am facing an error that says "Uncaught TypeError: Cannot read property 'coSearchCriteria' of undefined" while testing, even though the normal functionality of the co ...

Unit test does not show the PrimeNG menubar start directive

Currently, I am in the process of writing Jasmine tests for my component which includes PrimeNG's menubar. Within this component, I am utilizing the start template directive in the following manner: <p-menubar id='menubar' [model]='i ...

Is there a way to retrieve the number of swipe up interactions from Instagram story insights using the graph API

Is there a way to retrieve the swipe up count displayed in Instagram insights? Since Facebook does not provide this data through their Graph API, how can I access it? I have already tried scraping without success and I am looking for a solution using eith ...

Strategies for handling uncaught promise rejections within a Promise catch block

I'm facing a challenge with handling errors in Promise functions that use reject. I want to catch these errors in the catch block of the Promise.all() call, but it results in an "Unhandled promise rejection" error. function errorFunc() { return ne ...