Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enum in Angular 2 templates

Tags:

angular

I am trying to use enum in angularjs 2 templates. Below is my code

@Component({     selector: 'test',     template: ` <ul class="nav navbar-nav">     <li class="{{activeSection == SectionType.Primary ? 'active': ''}}"><a href="javscript:void(0);" (click)="setActiveSection(SectionType.Primary)">Primary Details</a></li>     <li class="{{activeSection == SectionType.Aditional ? 'active': ''}}"><a href="javscript:void(0);" (click)="setActiveSection(SectionType.Aditional)">Additional Details</a></li>     <li class="{{activeSection == SectionType.Payment ? 'active': ''}}"><a href="javscript:void(0);" (click)="setActiveSection(SectionType.Payment)">Payment Settings </a></li>              </ul>`   })   export class TestComponent{   activeSection: SectionType = SectionType.Primary;    setActiveSection(section: SectionType) {         this.activeSection = section;     } } 

here is my enum:

enum SectionType {     Primary,     Aditional,     Payment } 

It is throwing EXCEPTION: TypeError: Cannot read property 'Primary' of undefined

like image 252
Prem Parihar Avatar asked May 17 '16 13:05

Prem Parihar


People also ask

Can I use enum in template angular?

The TypeScript enum can be used directly in your class, but it has to be assigned to a local variable to be used in the template. The template can work only with your local variable and not the enum self. The template can access only objects exposed by the controller or the component.

Can I use enum in HTML angular?

Enums can be used in your Angular templates. This is handy for situations like avoiding a hard coded set of values for a dropdown menu or displaying different content based on your component state.

What are enums in angular?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases.

What is enum variable?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.


1 Answers

The simple way to use an Enum in a template is

@Component(...) export class MyComp {   public MyEnum: any = MyEnum; } 

Then in template:

<select>   <option value="MyEnum.ValueA">Value A</option> </select> 
like image 69
jkyoutsey Avatar answered Sep 21 '22 02:09

jkyoutsey