Is it possible to modify an enum in Angular depending on a condition?

Recently, I decided to create an enum that holds some commonly used colors throughout my application.

export enum SeverityColor {
    None = '#2196F3',
    Low = '#39B54a',
    Medium = '#FCEE21',
    High = '#F7931E',
    Critical = '#F44336',
}

Now, the team is exploring adding a theme switch feature - transitioning between dark and light modes. In order to achieve this, the colors defined in the enum must dynamically update based on the active mode. While it may not be considered best practice, I am wondering if there is a way to update this Enum conditionally rather than manually modifying each reference in the codebase.

If anyone has any suggestions or alternative approaches to tackle this challenge, I would greatly appreciate your input. Thank you!

Answer №1

The topic at hand is all about typescript. In simpler terms, enums in typescript are essentially converted to a basic javascript object during the compilation process. This implies that from a javascript viewpoint, it would be feasible to create something similar to this:

SeverityColor.Low = '#BADA55';

Nevertheless, typescript will raise an objection if you attempt this, indicating that Low is set as readonly. One way to get around this restriction is by asserting the type to any, as shown below:

(SeverityColor as any).Low = '#BADA55';

In my opinion, I don't consider this approach to be very prudent, but hey, it's an option.

Answer №2

While attempting to incorporate a ternary operator within the enum, I encountered an issue: The problem at hand is that 'string' cannot be assigned to type 'number' as mandated for computed enum member values. From what I grasp, there exists a distinction between const-based and string-based enums, where in a string-based enum, string values are handled before being allocated to the member key. Though I vaguely recall resolving this dilemma by utilizing a type or const assertion, or by casting the member value some time back, I believe the most optimal approach would be to use:

const isDark = window.matchMedia("(prefers-color-scheme:dark)").matches
or
const currentTheme = document.documentElement.getAttribute("data-theme")
to choose between light and dark mode using two sets of enum SeverityColor.

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

Leverage JavaScript Object Properties within Angular 5 Components

Here's a question I have on using ngx-charts in Angular 5. I am experimenting with ngx-charts to create a chart within my Angular 5 project. The code snippet for my component is shown below: import { Component, OnInit } from '@angular/core&ap ...

Remember to always call "done()" in Typescript + Mocha/Chai when dealing with async tests and hooks. Additionally, when returning a Promise, make sure it resolves correctly

It seems like I'm facing an old issue that I just can't seem to resolve, despite trying everything in my power. The error message reads: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Pro ...

Frequent occurrence when a variable is utilized prior to being assigned

I am currently working with a module import pino, { Logger } from 'pino'; let logger: Logger; if (process.env.NODE_ENV === 'production') { const dest = pino.extreme(); logger = pino(dest); } if (process.env.NODE_ENV === &apo ...

Creating SVGTextElement elements with appropriate types prior to appending them

I am in need of dynamically creating multiple text elements based on provided data. These text elements should be enclosed within a rectangle that matches the width of the text element with the largest width, similar to this example: https://i.sstatic.net ...

What is the best way to include a json file in an AngularJS controller of a MEAN stack app being run locally?

I am having difficulties including a json file containing data in a locally running mean stack app. Despite trying multiple methods, I continue to encounter a persistent 404 error. $http.get('MOCK_DATA.json').success(function (res){ $scope. ...

I am having issues with npm starting properly as it is unable to locate the module 'worker_threads'

My current versions are node: v10.24.0 and npm: 6.14.11. When I try to run my Angular frontend using ng serve, I encounter the following error: ng serve An unhandled exception occurred: Cannot find module 'worker_threads' Check "/tmp/n ...

Issues with getOptionLabel in Material UI

I have a constant with the following values : const Reference = [ { label: "RF-100", year: "Test" }, { label: "RF-200", year: "Test2" }, { label: "RF-300", year: "Test3" }, ]; and my Autoco ...

"How can I dynamically set the text for a radio button using Reactive Forms? Also, how do I capture the selected radio button value and the question title

If I use a reactive form-array, can I dynamically add 2 questions and 3 or 4 choices? Question 1: How do I set the radio button text dynamically using form-array? Question 2: Now, I'm attempting to retrieve only the selected choice ID corresponding ...

Exploring the power of props in Vue3/Nuxt3: A guide to utilizing props directly in the

Could you assist me in resolving this issue : When accessing a value from the props within the root scope of <script setup>, reactivity is lost (vue/no-setup-props-destructure) The technologies I am using include : nuxt: "^3.6.5" typescri ...

Data Binding in Angular using TypeScript Classes

Within my component, I have defined a property that is linked to the UI. Component export class MyComponent implements OnInit { public propertyA: string; public propertyB: string; } UI <textarea matInput rows="10" placeholder="Body" [(ngM ...

Different Ways to Validate Angular 2 FormGroups

Component: ngOnInit() { this.record = new FormGroup({ movement: new FormControl(''), weight: new FormControl('', [Validators.required, Validators.pattern('^[0-9]*$')]), date: new FormControl('' ...

Ordering an array in Angular 2: A step-by-step guide

I am working on an Ionic 2 app with an older version of AngularJS that does not have the orderby pipe by default. As a result, I have an array structured like this: <div *ngFor="let boatBooking of boatBookings" style="padding: 0px; margin:0px;"> ...

Angular 6 - Struggling to translate "Invalid Date" to a valid date using the "DatePipe" filter

Greetings, I am encountering an issue related to converting dates into a specific format that I desire. Currently, the REST API is sending dates in Milliseconds format, which I need to convert to a date format like yyyy-MM-dd for my date-picker component ...

What are the steps for customizing the interface in TypeScript?

After fixing a type error related to adding custom functions to the gun chain by including bind():any within IGunChainReference in @types/gun/index.ts, I am wondering how to transfer this modification to one of my project files. I have not been able to fi ...

Is there a way to successfully deploy an angular 6 application on wamp?

Could I possibly install my Angular 6 application on an Apache server, or is that not a feasible option for me? I'd prefer not to use nginx. Can the application successfully run on an Apache server? ...

The Angular 2 Code Snippet extension created by Mads is experiencing issues within Visual Studio 2017

Even though I have a collection of snippets at my disposal, I am facing an issue where I am unable to see them when I enter "ng". The only thing that appears is what is shown in the image below. Could it be possible that Resharper is causing this override? ...

Type definitions in Typescript for the style property of Animated.View

One of my components has a Props interface that extends ViewProps from React Native, like this: export interface Props extends ViewProps { // Custom props } As a result, this also extends the style prop. However, I am facing an issue while using Animat ...

Should I opt for 'typeof BN' or the BN Constructor when working with TypeScript and "bn.js"?

Note: Despite the recommendation to use BigInts instead of bn.js, I am currently working with a legacy codebase that has not been migrated yet. Below is the code that compiles and executes without any issues: import { BN } from "bn.js"; import a ...

Having trouble getting @types/express-session to function properly. Any suggestions on how to fix it?

My web-app backend is built with TypeScript and I've integrated express-session. Despite having @types/express and @types/express-session, I continue to encounter type errors that say: Property 'session' does not exist on type 'Request ...

Component in Angular2 encountering a null value

Unexpected situations may arise where "this" becomes null within a component. So far, I have encountered it in two scenarios: 1) When the promise is rejected: if (this.valForm.valid) { this.userService.login(value).then(result => { ...