1

I'm trying to change template with enum values.
TS:

enum NumType {
  first, second, third
}

@Component({
  selector: 'app-test',
  template: `
      <div [ngSwitch]="numType">
        <a *ngSwitchCase="numType.first" href="first">first</a>
        <a *ngSwitchCase="numType.second" href="second">second</a>
        <a *ngSwitchCase="numType.third" href="third">third</a>
      </div>
  `,
})
export class TestElementComponent {
  @Input() readonly numType: NumType;
}

HTML:

<app-test
[numType]="numType.first"
></app-info-element>  

And then I've got this error:

ERROR TypeError: Cannot read property 'first' of undefined

Can you please tell me what needs to be done to make it work?
Angular 8 used.

BondBill
  • 11
  • 3

1 Answers1

2

in .html only can use variables that belong to the component. So, if you use a enum you should use a variable in your component. It's the reason generally you use a .ts with definitions

//definitions.ts
export enum NumType { //<---see the word "export"
  first, second, third
}

Your main component

   import {NumType} from './definitions'
   numType=NumType

   //now you can use
   <app-test [type]="numType.first"></app-test>  

Your app-test sould import also the "NumType"

   import {NumType} from './definitions'

   numType=NumType
   @Input() type:NumType  //<--the input has no possible called "numType"

   //now you can use -see that the "switch" is about "type"
   <div [ngSwitch]="type">
        <a *ngSwitchCase="numType.first" href="first">first</a>
        <a *ngSwitchCase="numType.second" href="second">second</a>
        <a *ngSwitchCase="numType.third" href="third">third</a>
   </div>

the stackblitz

BTW, you're using <a href>, if you want to work with angular you should use

 <a routerLink="....">

see the docs

Eliseo
  • 50,109
  • 4
  • 29
  • 67