How to pass enum value in angular template as an input?
Asked Answered
S

1

5

I have a child component which takes type as an input
child component :

export enum PersonTypes {
  MALE = 'male',
  FEMALE = 'female'
}
@Component({
  selector: 'app-child'
})
export class ChildComponent {

  @Input() type: PersonTypes;
}

Parent component:

@Component({
  selector: 'app-parent'
})
export class ParentComponent {

}

In the Parent component View template:

 <div>
     <app-child [type]="PersonTypes.MALE"></app-child>
     <app-child [type]="PersonTypes.FEMALE"></app-child>
 </div>

so , the question is how to pass the different enum values in the template ? i found one answer saying we need create a new variable in parent component and then assign that value to "type" in the template like below.

@Component({
  selector: 'app-parent',
  template:` <div>
     <app-child [type]="malePerson"></app-child>
     <app-child [type]="femalePerson"></app-child>
 </div>  `
})
export class ParentComponent {
        malePerson = PersonTypes.MALE;
        femalePerson = PersonTypes.FEMALE;
    }

for me it is over killed solution , what if we have 10 enum properties , we end up creating 10 local variables and assigning them in the template is too much.

any better solution for this ?

Saxe answered 13/10, 2021 at 4:54 Comment(0)
S
11

To use Enum in the template you just have to directly assign the Enum to the component public property.

@Component({
  selector: 'app-parent'
})
export class ParentComponent {
public PersonTypesEnum = PersonTypes; // direct reference 
}

Now PersonTypesEnum can be used in a template

<div>
     <app-child [type]="PersonTypesEnum.MALE"></app-child>
     <app-child [type]="PersonTypesEnum.FEMALE"></app-child>
 </div>
Skylar answered 13/10, 2021 at 5:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.