jack miao jack miao - 4 months ago 33
AngularJS Question

cant pass enum type properly in html

I want to pass an enum type in my html to a method.

export enum ListType {typeOne, typeTwo, typeThree}


now in my button click I want to do this:

<button md-button
(click)="setListToDisplay(ListType.typeOne)"
class="md-primary">Matcher
</button


this is the function in the component.ts

public setListToDisplay(type: ListType):void {
switch (type) {
case ListType.matcherView:
this.listToDisplay = this.listOneToDisplay;
case ListType.expediteView:
this.listToDisplay = this.listTwoToDisplay;
case ListType.typeThree:
this.listToDisplay = this.listThToDisplay;
}
}


this is my error:


TypeError: Cannot read property 'length' of undefined in
[listToDisplay in MyCmp@62:57]


but it dosent work, how should I do it properly?

Answer

You have to create a property inside the @Component-decorated class for you to be able to reference the enum at the template.

So if you have a template/code similar to the one below, add the property as showed:

import { stuff } from 'whatever';
...

export enum ListType {typeOne, typeTwo, typeThree}

@Component({
  selector: 'my-component',
  template: `
  ...
  <button md-button
          (click)="setListToDisplay(ListType.typeOne)"
          class="md-primary">Matcher
  </button>
  ...
  `
  ...
})
export class MyComponent {

  public setListToDisplay(type: ListType):void {
    switch (type) {
      case ListType.matcherView:
        this.listToDisplay = this.listOneToDisplay;
      case ListType.expediteView:
        this.listToDisplay = this.listTwoToDisplay;
      case ListType.typeThree:
        this.listToDisplay = this.listThToDisplay;
    }
  }

  // add a property with the enum name, like this:
  public ListType = ListType;    // <<<-------------------------------- add this property 

  // with the above you can now use the ListType.typeOne in the template.

}
Comments