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
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With