Having trouble retrieving an Enum within an Angular template?

I am trying to use an enum to read a property of an array. However, I encountered an error with the following code:

<ng-container *ngFor="let elem of list">
  <div class="ui-g-12 ui-sm-12 ui-md-12  ui-lg-12 ui-xl-12">
    <div class="ui-g-12 ui-sm-12 ui-md-12 ui-lg-3 ui-xl-3">
      <input type="text" pInputText value="{{elem[StudentEnum.name] }}" name="student_name" />
    </div>
</ng-container>

The StudentEnum is an enum class, but when I try to use it in the template it doesn't work. Can someone guide me on the correct approach to reading array properties and values using an enum in a template?

{{ elem[StudentEnum.name] }}

Answer №1

When using the interpolation syntax {{ }}, the variables are limited to the scope of the corresponding component's class and do not have access to variables like StudentEnum that are defined outside that scope.

Approach 1: Local member variable

One solution is to create a local member variable to store the enum. Here's an example:

import { StudentEnum } from './model/student.enum.ts';

@Component({...})
export class SomeComponent implements OnInit {
  public studentEnum = StudentEnum;  // <-- assign the enum to a member variable

  ...
}
<!-- Note the use of `studentEnum` with a lowercase `s`. This refers to the member variable -->

<input type="text" pInputText value="{{elem[studentEnum.name] }}" name="student_name"/>

Approach 2: Pipe

If you prefer not to create a local member variable for each component, you can create a pipe to retrieve the enum value as needed.

For instance

student.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { StudentEnum } from './model/student.enum.ts';

@Pipe({
  name: 'student',
  pure: true,
})
export class StudentPipe implements PipeTransform {
  transform(value: any): any {
    if (!value) {
      return null;
    }
    return StudentEnum[value];
  }
}

Then use it in the template

<input type="text" pInputText value="{{elem['name' | student] }}" name="student_name"/>

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

Angular15: How can we properly provide support for legacy browsers?

I'm having issues with my Angular build on IOS12 as it's only displaying a blank page. Below are the dependencies listed in my package.json: "dependencies": { "@angular/animations": "^15.0.0", "@angular ...

After each save, gulp-typescript is emitting errors, however, it works without any issues upon subsequent saves

I'm facing some uncertainty regarding whether the issue I'm encountering is related to gulp, typescript, or Angular 2. Currently, I am using Angular 2 Beta 6. Here is an example of my typescript gulp task: var tsProject = p.typescript.createPr ...

Using angular2's ngRepeat to iterate over XML data

I have successfully transformed my XML data into JSON format to be utilized in Angular 2 within my view. However, as I attempt to loop through the data using a for(var... loop, I encounter an error message stating that it cannot find name array and that th ...

Setting up an empty array as a field in Prisma initially will not function as intended

In my current project using React Typescript Next and prisma, I encountered an issue while trying to create a user with an initially empty array for the playlists field. Even though there were no errors shown, upon refreshing the database (mongodb), the pl ...

Instructions for utilizing ObjectId with a string _id on the client side

Is there a way to retrieve a document using the _id in string format? Here is an example of the code on the client side: 'use client' ... const Page(){ ... fetch("api/get_data", { method: 'POST', ...

How to customize Material UI Autocomplete options background color

Is there a way to change the background color of the dropdown options in my Material UI Autocomplete component? I've checked out some resources, but they only explain how to use the renderOption prop to modify the option text itself, resulting in a a ...

What are the properties used in functional components of React?

Seeking guidance on passing React component props to another component: interface IMyComponent { props: Props<any> } const MyComponent: FC = ({ props }) => { } Previously, I attempted to utilize the React.Props type after consulting this que ...

Tips for properly importing types from external dependencies in TypeScript

I am facing an issue with handling types in my project. The structure is such that I have packageA -> packageB-v1 -> packageC-v1, and I need to utilize a type declared in packageC-v1 within packageA. All the packages are custom-made TypeScript packa ...

The interface is unable to populate the Array of Elements

When using Angular, I send a request and save the response in a variable: conversations: Conversation[]; // ChatService getConversations() { return this.http.get<Conversation[]>('/chat/conversations'); } this.chatService.getConversat ...

What is the best way to create a function that can securely search for a URL containing parameters while ensuring type safety?

I am working on a NextJS/React application. We have a large object containing internal URLs, each with a createPath function that looks similar to this: const URLS = { dashboard: { createPath: ({ accountNumber }: { accountNumber: string }) => ...

The W3C Validator has found a discrepancy in the index.html file, specifically at the app-root location

While attempting to validate my HTML page, I encountered the following error: Error: Element app-root not allowed as child of element body in this context. (Suppressing further errors from this subtree.) From line 4347, column 7; to line 4347, column 16 ...

What is the process for defining a state using React Native and TypeScript?

Recently, I've embarked on my journey with React Native and decided to incorporate TypeScript into my development process. As I attempted to set my state, an error popped up that reads as follows: An issue arose while trying to assign the argument &a ...

Tips for getting Angular Ivy and Angular Universal up and running together

I'm encountering a problem while attempting to incorporate Ivy + Angular Universal into my project. This issue only arises when I enable Ivy mode in Angular (disabling it allows me to successfully build my application). Below are the steps to replic ...

What is the purpose of the 'unique' keyword in TypeScript?

While coding in the TypeScript playground, I stumbled upon a situation where the term unique seems to be reserved. However, I haven't been able to find any official documentation regarding this. https://i.stack.imgur.com/eQq5b.png Does anyone know i ...

We were caught off guard by the TypeScript error: an unexpected token showed up when we were expecting a constructor,

Trying to implement a function within a class in TypeScript. class Test { function add(x: number, y: number): number { return x + y; } } Encountering an error message stating: TypeScript Unexpected token, A constructor, method, access ...

Encountering issues with redirecting the URI when using Oidc-client in an Angular2 application with hash

I am currently following a tutorial on Authenticating Angular2 with Oidc-client and attempting to incorporate the authentication aspect into my project. Since Angular2 is using { provide: LocationStrategy, useClass: HashLocationStrategy } my URLs are no ...

The absence of a semicolon following the interface declaration is the issue

I am facing a slight issue with ESLint and Typescript, particularly regarding semicolons after declaring interfaces. Additionally, I utilize VSCode as my editor with automatic formatting upon saving. Below is the configuration in my .eslintrc.json file: ...

Initializing various objects on the same interface type array in one line

Is there a way to inline initialize an array of the interface type IFooFace in TypeScript with different specific implementations, similar to how it can be done in C#? Or do I have to initialize my objects before the array and then pass them in? In C#, th ...

Setting up Typescript with React 17 and Tailwind CSS version 2.0

I'm struggling to set up TailwindCSS 2.0 with the create-react-app --template typescript configuration and encountering errors. Even after following the instructions on the official TailwindCSS website for React at https://tailwindcss.com/docs/guides/ ...

Looking to retrieve HTML elements based on their inner text with queryselectors?

I am looking to extract all the HTML divs that contain specific HTML elements with innerText = ' * ' and save them in an array using Typescript. If I come across a span element with the innerText= ' * ', I want to add the parent div to ...