The implementation of enumerations in Angular's HTML pages

I'm working with an enum in Angular 13 and I want to use it in a component.

Enum:

export enum PropertyCode {
  ALPHA = 'ALPHA',
  BETA = 'BETA',
  ZETA = 'ZETA',
}

TS:

import { Component, VERSION } from '@angular/core';
import { PropertyCode } from './property-code';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {

  isHidden(code: PropertyCode): boolean {
    switch (code) {
      case PropertyCode.ALPHA:        return false;
      case PropertyCode.BETA:        return true;
      case PropertyCode.ZETA:        return false;
    }
  }
}

HTML:

<ul>
  <li *ngIf="!isHidden(PropertyCode.ALPHA)">Alpha</li>
  <li *ngIf="!isHidden(PropertyCode.BETA)">Beta</li>
  <li *ngIf="!isHidden(PropertyCode.ZETA)">Zeta</li>
</ul>

Result:

https://i.sstatic.net/oMO8I.png

Sandbox here

My goal is to avoid creating a property for the enum in the component...

It's unnecessary as there's no specific data to store, and I prefer using UpperCase letters in the HTML, like a standard enum.

So, I attempted using a decorator

import { PropertyCode } from './property-code';

export function PropertyCodeAware(constructor: Function) {
  constructor.prototype.PropertyCode = PropertyCode;
}

and applied the decorator to the component, but it didn't solve the issue

@PropertyCodeAware
export class AppComponent {

Answer №1

A brilliantly straightforward approach suggested by Jorge Mussato, within the .component.ts

public fetch PropertyCode() {
  return PropertyCode; 
}

Decorators not necessary (to be omitted)

Answer №2

First step is to declare a property within your AppComponent class

propertyCodes = PropertyCodes;

Once you have done that, you can reference this property in your app.component.html file

<ul>
  <li *ngIf="!isHidden(propertyCodes.ALPHA)">Alpha</li>
  <li *ngIf="!isHidden(propertyCodes.BETA)">Beta</li>
  <li *ngIf="!isHidden(propertyCodes.ZETA)">Zeta</li>
</ul>

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

What is the best way to ensure that decimal numbers are shown in the right locale number format by default in an Ionic/Angular app

I am currently working on an Ionic/Angular application that frequently requires the display of decimal numbers on its pages. The LOCALE_ID in my app is set to "cs", so I expect numbers to be displayed using this locale. Ideally, "1,000.23" would display as ...

Endless refreshing on ionic serve even when there are no file modifications

Issue Description While testing my ionic application build using the ionic serve command, I noticed that the app keeps recompiling as if triggered by a live reload, even when no files have been changed. This continuous recompilation process persists indef ...

Waiting for an observable to load the page in Ionic 2

When loading a page that calls an API to fetch objects for display, I encounter an issue where the page finishes loading before any data is received, resulting in an empty display. constructor(public navCtrl: NavController, public userData: UserData, publ ...

Determining the return type based on the parameter type

Here is an example of my function: const safeIdCastToNumber = (id: string | null | undefined) => isNil(id) ? id : Number(id) When calling safeIdCastToNumber, I can use an id parameter with a type union string | null | undefined, as well as one with a t ...

Creating Excel documents using Angular and XLSX template generator

In my Angular application, I am utilizing the XLSX library to manipulate an Excel file. The file I start with is encoded in base64 format, so my first task is to decode it, make some changes to specific cells, and then save the modified file back in base64 ...

Expanding a TypeScript interface across different modules

For my project, I am working with Highcharts typings and encountered a need to extend certain object/interfaces it defines by adding some custom properties. Here is an example: declare namespace Chart { interface ChartOptions extends Highcharts.ChartOpt ...

Tips for obtaining the "inner type" of a particular "instance" in TypeScript's generics

Unable to find more appropriate language to elaborate beyond the title, I'm going to rely on the code itself: let var1 = someExternalLibraryMethod(); // assume var1 is implicitly Promise<string> let var2: typeof var1; // this approach enables ...

React: The useContext hook does not accurately reflect the current state

I'm currently facing a dilemma as I attempt to unify data in my app. Whenever I click the button, the isDisplay value is supposed to be set to true; even though the state changes in my context file, it does not reflect in the app. Thank you for your ...

React 18 update causes malfunctioning of react-switch-selector component

I'm facing an issue where the component is not rendering. I attempted to start a new project but it still didn't work. Is there a solution to fix this problem or should I just wait for an update from the original repository? Encountered Error: ...

Essential front-end tools for enhancing Angular 2 projects

Hi there! I specialize in Laravel development and am currently diving into the world of Angular 2 framework. Up until now, I've been handling my third-party front end assets through bower, using a bower.json file to manage dependencies. Check out a sn ...

Certain Bootstrap components are malfunctioning within an Angular application

I've been encountering issues while working on a project that involves Bootstrap and Angular. Certain elements like dropdowns, accordions, etc. are not functioning properly. Interestingly, these components work perfectly fine when tested in separate ...

Tips for preventing error TS2345 when importing TypeScript components from outside the project directory in Vue

Encountered the following TypeScript error when attempting to use a component outside of the project directory: TS2345: Argument of type '{ template: string; components: { SimpleCheckbox: typeof SimpleCheckbox; }; }' is not assignable to paramet ...

How to implement a Typescript interface without necessarily implementing the parent interfaces

Within my current project, I have defined the following interfaces: interface foo { fooProperty: number; fooFunction(): void; } interface bar extends foo { barProperty: string; barFunction(): void; } Now, I am interested in creating a class like ...

Change the ddmmyy date string to dd/mm/yyyy format using TypeScript

When I use the date picker onchange method, the date is passed as a string like ddmmyyyy (20102020) to dd/mm/yyyy. I am unsure of how to convert the date format from ddmmyyyy to dd/mm/yyyy. In the CustomDateParserFormatter, the string needs to be converted ...

Differentiate the array type within an object in TypeScript

I understand how to specify the type for a variable. let members: string[] = [] // this example works flawlessly My goal is to have an array of strings within an object. How can I structure it correctly? const team = { name: String, members<st ...

Can anyone tell me the source of this switchmap's argument?

Currently, I am enrolled in Jogesh Muppala's Angular course on Coursera and encountered an issue with the code snippet below. this.route.params.pipe(switchMap((params: Params) => this.dishService.getDish(+params['id']))) The remaining c ...

What is the process for deploying a Lambda function using Terraform that has been generated with CDKTF

Currently, I am following a tutorial by hashicorp found at this link. The guide suggests using s3 for lambda deployment packages. // in the process of creating Lambda executable const asset = new TerraformAsset(this, "lambda-asset", { ...

Leverage glob patterns within TypeScript declaration files

Utilizing the file-loader webpack plugin allows for the conversion of media imports into their URLs. For example, in import src from './image.png', the variable src is treated as a string. To inform TypeScript about this behavior, one can create ...

Is there a way to retrieve just one specific field from a Firestore query instead of fetching all fields?

I am experiencing an issue where I can successfully output all fields in the console, but I only want to display one specific field. In this case, I am trying to retrieve the ID field but I am encountering difficulties. Below are screenshots illustrating m ...

Adjusting the selection in the Dropdown Box

I've been attempting to assign a value to the select box as shown below: <dx-select-box [items]="reportingProject" id="ReportingProj" [text]="reportingProject" [readOnly]="true" > ...