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

At what point is the ngOnInit function invoked?

Here is the code snippet I am working with: <div *ngIf="hotels$ | async as hotels; else loadGif "> <div *ngFor="let hotel of hotels | hotelsFilter: _filteredType; first as f; index as i " appInit [hotel]="hotel " [first]="f "> < ...

Unable to trigger an event from an asynchronous method in TypeScript

In my scenario, I have a child component that needs to emit an event. However, I require the parent handler method to be async. The issue arises when the parent does not receive the emitted object in this particular configuration: Parent Component <co ...

Mastering the integration of NestJS with Redis for microservices

Currently, I am diving into the world of nestjs microservices. I am curious, what commands are available for me to use? const pattern = { cmd: 'get' }; this.client.send<any>(pattern, data) Additionally, how do I go about retrieving data ...

Unlinking checkbox click event from row in Angular Material table

I am seeking to remove the ability for row selection in my table rows so that clicking anywhere within the row does not check the checkbox. I want the checkbox to only be checked when the box itself is clicked, allowing me to later add expandable rows when ...

What do I do when I encounter the error message "Provider not found for RadioControlRegistry" in Angular 2? Which provider should

Which provider should be included in the provider component? <div class="radio"> <input let match id="male" type="radio" name="gender" value="true" [(ngModel)]="isMatching" (click)="isMatching(match.value)" > Take a look at my console output ...

Testing the navigation functionality in Angular 6 by unit testing the "go back

Seeking a straightforward method for unit testing the location go back functionality. main.ts import { Component, OnInit } from '@angular/core'; import { Location } from '@angular/common'; @Component({ selector: 'app-product-i ...

Generating Legible JavaScript Code from TypeScript

I am looking to maintain the readability of my compiled JS code, similar to how I originally wrote it, in order to make debugging easier. However, the typescript compiler introduces several changes that I would like to disable. For instance: During compi ...

Using Next.js and TypeScript to Send Props to Dynamically Typed Objects

I am in the process of developing an application using Next.js with TypeScript. I have encountered an error message stating Type 'VoidFunctionComponent<ShirtDetailProps>' is missing the following properties when passing props to a component ...

Angular 2: Issue with Component not reinitializing when query parameters change

I am currently working with Angular 2 and the latest router component to create a search functionality. Upon clicking the search button for the first time, the router navigates to the search component and retrieves data from the service. However, I have no ...

Incorporating TypeScript basics into the if statement post compiling

As I delve into the Angular2 Quickstart, I stumbled upon a peculiar issue within app.component.js after compiling app.component.ts using tsc (version 1.8.2): if (d = decorators[i]) I am unable to pinpoint where I may have gone wrong in configuring the qu ...

Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet: import React, { useState } from 'react' const App = () => { const data = [ ['Hotel 1A', ['A']], ...

AngularJS2 brings a powerful and seamless implementation of indexedDB for efficient

I'm on the hunt for an indexeddb implementation that works seamlessly with Angularjs2. While I stumbled upon this api at https://github.com/gilf/angular2-indexeddb, it appears to be lacking in active development and may not be ready for production use ...

Change object values to capital letters

Upon retrieving myObject with JSON.stringify, I am now looking to convert all the values (excluding keys) to uppercase. In TypeScript, what would be the best way to accomplish this? myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", ...

What is the best way to connect input values with ngFor and ngModel?

I am facing an issue with binding input values to a component in Angular. I have used ngFor on multiple inputs, but the input fields are not showing up, so I am unable to push the data to subQuestionsAnswertext. Here is the code snippet from app.component ...

Testing an Angular hybrid application resulted in the error message "Unable to access property 'nativeElement' of null."

I'm encountering a problem with a straightforward test: it ('should be able to navigate to add program', fakeAsync(() => { let href = fixture.debugElement.query(By.css('.add-program-btn')); let link = href.nativeElement.get ...

Troubleshooting a problem with Angular2 involving the This.http.get function

Currently, I am delving into Angular 2 and have set up an ASP.NET WebApi locally hosted in IIS at http://localhost:8081/ping. The API call successfully returns a string serialized as a JSON Object. Below is the code for my service: import { Injectable } ...

Is it possible to upgrade just the rxjs version while keeping all other components at their current versions?

While working on my Angular 4 project, I encountered a problem when trying to use a WebSocket package from GitHub. After running npm install to upgrade the rxjs version, I faced errors. Even after attempting to upgrade just the rxjs version and running ng- ...

Transitioning from angular version 5.2 to the latest angular 6.1 version

Currently, I find myself on node 8.11 and utilizing VS code. The project was originally built in version 5.2.5 but has been inactive for some time now. Within my project, the following modules are present: import { BrowserModule } from '@angular/plat ...

Having difficulties incorporating a selected custom repository into a module

Issue with Dependency Injection in NestJS Currently, I am working on implementing SOLID principles in my NestJS project by decoupling my service layer from TypeOrm. One of the benefits of this approach is the ability to switch between using an InMemoryRep ...

The TypeScript error "Issue with Type Assertion: 'This expression is not callable Type'...' has no call signatures" occurs when there is a missing semicolon

Here's a simplified version of our original code: const start: number = 10 const end: number = 20 (someElement as HTMLInputElement).setSelectionRange(start, end) We encountered an error with the 20, where a red squiggly line appeared indicating ...