What is the best way to send an enum from a parent component to a child component in

I'm trying to send an enum from a parent component to a child component.

This is the enum in question:

export enum Status {
  A = 'A',
  B = 'B',
  C = 'C'
}

Here's the child component code snippet:

@Component({
  selector: 'app-enum-selection',
  templateUrl: './enum-selection.component.html',
  styleUrls: ['./enum-selection.component.scss']
})
export class EnumSelectionComponent implements OnInit {

  @Input() enum: Object;
  enumKeys=[];

  constructor() { 
    this.enumKeys=Object.keys(this.enum);  
  }

  ngOnInit(): void {
  }
}   

This is how I'm utilizing the child component within the parent component:

<app-enum-selection [enum]="Status"></app-enum-selection>

However, despite passing the Status enum to the component, the value is always null. Why isn't the Status being transferred to the component? How can I effectively pass an enum from a parent to a child component?

Answer №1

Make sure to assign the Enum to a property of the main component. For example:

let selectedEnum = MyEnum;

Next, pass this property as an input to the child component:

<app-custom-component [enumProperty]="selectedEnum">

Answer №2

An enumeration is a defined type, not a variable itself. When working with enums, you pass a variable that holds a value from that enum. Instead of specifying the [enum] as "Status" (which is the type), you would implement it like this:

// Note: The enum should be in its own file for easy importing into both parent and child components.

export enum Status {
  A = 'A',
  B = 'B',
  C = 'C'
}

// In the parent component
public myStatus: Status = Status.A;

Then, in your parent's HTML:

<app-enum-selection [statusValue]="myStatus"></app-enum-selection>

The child component needs to make adjustments like so:

import { Status } from './wherever-the-file-lives';

@Input()
public statusValue: Status;

Answer №3

There is no need to pass the enum if you intend to use it in a child component. You can simply import the enum directly into the child component.

In the child TypeScript file:

import { Status } from 'path-to-enum-file.ts';
@Component({
 selector: 'app-enum-selection',
 templateUrl: './enum-selection.component.html',
 styleUrls: ['./enum-selection.component.scss']
})
export class EnumSelectionComponent implements OnInit {
 enumKeys=[];

 constructor() { 
 this.enumKeys=Object.keys(Status);
 }

 ngOnInit(): void {
 }
} 

If you wish to use the enum in the child HTML, do the following in the TypeScript file:

Status = Status;

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

Error: Your call to the "useFormState" function does not match any available

I am fairly new to web application development and I'm facing an issue with the useFormState function. I am currently working on building an edit form for database entries, but the code that previously worked is now throwing an error stating that ther ...

Creating void functions in TypeScript

I encountered a section of code within a custom component that is proving to be quite puzzling for me to comprehend. public onTouch: () => void = () => {} The function onTouch is being assigned by the private method registerOnTouch(fn: any) { ...

"Hmm, the React context's state doesn't seem to be changing

I have been working on a next.js app and I encountered an issue related to using react context to export a state. Despite my efforts, the state doesn't seem to update and it remains stuck at the initial value defined by the createContext hook, which i ...

Managing a Angular HTTP Request on a Bottle Server where CORS is restricted

I am encountering an issue while trying to send data from my Angular 9 App to a bottle backend server. When running the application on the client side, I receive a CORS (Cross-Origin Resource Sharing) error indicating that the 'Access-Control-Allow-Or ...

Guide to dynamically updating image URLs based on color selection in Angular when handling ngFor loop

component.ts // necessary imports have been included ngOnInit() { this.list = { 'eatList': [{ 'class': 'Fruits', 'color': ['Red', 'White', 'Black& ...

Introducing the 'node' type in tsconfig leads to errors in type definitions

I've encountered an issue with my NodeJS project where I have a type declaration file to add properties to the Request object: @types/express/index.d.ts: import { User } from "../../src/entity/user.entity"; declare global { namespace Exp ...

Seeking assistance with printing an HTML template using a printer in Angular 2. Can anyone provide guidance on how

I have a scenario where I need to print an HTML template from within my Angular 2 component. Specifically, I want to be able to click on a print button on the same page and trigger the print function, which would display a print preview and allow the use ...

Struggling to implement a singleton service in Angular as per the documentation provided

I have implemented a service in Angular that I want to be a singleton. Following the guidelines provided in the official documentation, I have set the providedIn property to "root" as shown below: @Injectable({ providedIn: "root" }) export class SecuritySe ...

Access the Angular directive instance before it is actually rendered

Is it possible to access an Angular directive instance even if it has not been rendered yet? Let's say I have an app-component and a baz-directive. I want to be able to get the directive instance even if it is not currently shown or rendered in the D ...

Building a custom Angular 6 pipe for generating a summary of a text snippet

Looking to create a pipe that limits the text box to only show the first 150 characters of the description. If the description is shorter than that, it should display the entire description followed by (...) Currently working on this: export class Tease ...

What is the procedure for linking the value (<p>John</p>) to the mat form field input so that it displays as "John"?

Can I apply innerHTML to the value received from the backend and connect it to the matInput? Is this a viable option? ...

What could be causing the Ioncol not triggering the Onclick event?

I am facing an issue where my onclick event is not working on an ion-col. The error message says that the method I call "is not defined at html element.onclick". Here is a snippet of my code: <ion-row style="width:100%; height:6%; border: 1px solid # ...

Troubleshooting Cross-Origin Resource Sharing (CORS) in a Spring Boot application:

We are currently working on a project that involves developing a spring boot and angularjs application. The authentication process includes the use of JWT token in combination with LDAP authentication. Once the LDAP authentication is successful, the servic ...

Is it feasible to append an element to the result of a function that returns an array?

Is it possible to push something to an array returned by a function, but not directly? Instead, I want to push it back into the function itself. hierar() { return [{ h: 1 }, { h: 2, hh: [{ u: 2.1 }, { u: 2.2 }] }, { h: 3, hh: [{ u: 4 }, { U: 5 } ...

Guide to combining an Angular 2 application with a Django application

Currently, I have been working through the Tour of Heroes tutorial. The structure of my Django app can be simplified as shown below: apps/my_app/migrations/ apps/my_app/__init__.py apps/my_app/urls.py apps/my_app/views.py frontend_stuff/js/ javascript ...

Unable to resolve TypeScript error: Potential 'undefined' object

Here is the code snippet that I am working with: const queryInput = useRef() const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault() if (queryInput && queryInput.current) { console.log(`queryInput.cur ...

Is TypeScript's Structural Typing the exception to the rule?

Let me illustrate two scenarios where I encountered difficulties. The first example involves two points: one in 2d and one in 3d: type Point2D = { x: number, y: number }; type Point3D = { x: number, y: number, z: number }; let point2D: Point2D = { x: 10, ...

How to add an item to an array in JavaScript without specifying a key

Is there a way to push an object into a JavaScript array without adding extra keys like 0, 1, 2, etc.? Currently, when I push my object into the array, it automatically adds these numeric keys. Below is the code snippet that I have tried: let newArr = []; ...

Unable to receive response from API in Ionic 4 Angular. Postman shows correct response

Ionic v4 Controller for Items: view image description here Response in DevTools -> I always receive data from the database - web application functions correctly view image description here Response from Postman: view image description here Please h ...

npm is unable to install a forked git repository in its current state

Attempting to install a customized version of ng2-smart-table on my application, but npm seems to be struggling with the process. I've experimented with various commands such as npm install git+http://github.com/myusername/ng2-smart-table.git npm i ...