How do I pass enum from parent to child component?

Viewed 457

I need to pass enum from parent to child component.

I have this enum:

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

and here is componenmt:

@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 {
  }
}   

Here how I use child component in parent component:

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

As you can see above I pass enum Status to the component but enum value is always null.

Why Status is not passed to the component? How do I pass enum from parent to child component?

3 Answers

You need to assign the Enum to an attributte of the parent component. Ex:

public myStatus = Status;

And then pass it on the input for the child component:

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

An enum is a type, not a variable. You don't pass a type, you pass a variable of that type. So instead of [enum]="Status" (which is a type), you would do something like this:

// note: the enum should be in its own file, so you can import it into both the parent and child components. 

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

// in parent component
public myStatus: Status = Status.A;

Then in your parent HTML:

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

The child component gets changed thusly:

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

@Input()
public statusValue: Status;

you dont need to pass enum if you want use it in child component you can directly use enum in child component by importing it

in child ts:

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 want to use it in child HTML do this in ts:

Status = Status;
Related