2

Using the Enum type in Angular library build an error as Can't resolve the enum while importing in other applications.

export enum Appearance {
    Basic = 0,
    Raised = 1,
    Stroked = 2,
    Flat = 3,
    Icon = 4,
    FAB = 5,
    MiniFAB = 6,
    Link = 7
}

After googling I found that I need to make the Enum as const. export const enum Appearance. But I can't make the enum const because I am using the Enum inside switch statement in HTML like below

<button mat-raised-button *ngSwitchCase="buttonTypes.Raised">{{field.componentProperty.label}}
    </button>
<button mat-raised-button *ngSwitchCase="buttonTypes.Stroked">{{field.componentProperty.label}}
    </button>
<button mat-raised-button *ngSwitchCase="buttonTypes.Flat">{{field.componentProperty.label}}
    </button>

export class ButtonComponent implements OnInit {
  buttonTypes = Appearance  ==============> declaring here
  constructor() { }
  ngOnInit(): void {
  }
}

Public-api.ts

export * from './lib/view-models/component-type.enum'

ERROR in ./src/app/user-module/users/car/car-search-filter/car-search-filter.component.ts
Module not found: Error: Can't resolve '@falcon-ng/core/lib/view-models/component-type.enum' in '/Users/macbook/Projects/RentalProjects/RentalUI/src/app/user-module/users/car/car-search-filter'

Is there any better solution ?

San Jaisy
  • 15,327
  • 34
  • 171
  • 290
  • do you use typescript extension for `component-type.enum` file e.g `component-type.enum.ts`? – deerawan May 03 '20 at 04:51
  • Yes I use the typescript file extension --> Apperence.enum.ts – San Jaisy May 03 '20 at 08:23
  • What works for me is: In file foo.ts: export enum AliasScoreValue { Good = 'GOOD', Neutral = 'NEUTRAL', Bad = 'BAD', ReallyBad = 'REALLY_BAD', } In file bar.ts: import { AliasScoreValue } from 'foo'; And then you can just assign it as you did. – Maria K. May 03 '20 at 10:06

1 Answers1

0

U can take either of the following 2 approaches:

EITHER try using the use the preserveConstEnums compiler flag as mentioned here - https://stackoverflow.com/a/45942840/5350404

OR directly use the enum value like so:

<button mat-raised-button *ngSwitchCase="RAISED">
  {{field.componentProperty.label}}
</button>
<button mat-raised-button *ngSwitchCase="STROKED">
  {{field.componentProperty.label}}
</button>
<button mat-raised-button *ngSwitchCase="FLAT">
  {{field.componentProperty.label}}
</button>
export class ButtonComponent {
  readonly RAISED = Appearance.Raised;
  readonly STROKED = Appearance.Stroked;
  readonly FLAT = Appearance.Flat;
}
batbrain9392
  • 565
  • 6
  • 15