Exporting enums in Angular modules
Asked Answered
V

2

7

Does anyone know if it’s possible to export enums in Angular modules? If not, are there any best practises to ship enums within Angular modules?

// not working example
// i dont know how to export GreatEnum

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { GreatComponent } from './great.component';
import { GreatEnum } from './great.enum';

@NgModule({
    imports: [
        CommonModule       
    ],
    declarations: [GreatComponent ],
    exports: [GreatComponent ]
})
export class GreatModule {
}
Varro answered 26/9, 2017 at 6:34 Comment(6)
show your enum fileLurleen
Like classes: https://mcmap.net/q/994467/-how-should-i-include-model-classes-in-an-angular-moduleVlada
What do you think you need to export? Why would you want to inject it using DI?Pentlandite
you can directly use them when you are using index.ts barrel fileButz
The enum file looks just like: export enum GreatEnum { 'foo' = 1, 'bar' = 2 }Bianco
In case you are looking how to use enums from a subcompent into the parents component - #35924244Limpid
K
8

Why you need to export enum from the modules?. It is not necessary . It is like an interfaces and classes. You can use it everywhere, except directly in the templates.

You can just import them in any file which you want and use there. For them there is no error like

Directive or Component is not found

Knockknee answered 26/9, 2017 at 6:38 Comment(2)
I'm writing modules for reusing them in several angular apps. Thats why I want to ship enums within the module.Bianco
Look. When you will add your modules in the packages of an application, you can export it from the barrel file of your package. It may contains for example export yourModule from yourFile; export yourEnum from yourEnumFile and then get your module and enum like import { YourModule, YourEnum } from YourPackage;Knockknee
S
11

If you are writing libraries, you have to export enums with the keyword const

export const enum <ENUM_NAME>
Saida answered 7/7, 2021 at 7:43 Comment(1)
Wish I could upvote more than once...Chive
K
8

Why you need to export enum from the modules?. It is not necessary . It is like an interfaces and classes. You can use it everywhere, except directly in the templates.

You can just import them in any file which you want and use there. For them there is no error like

Directive or Component is not found

Knockknee answered 26/9, 2017 at 6:38 Comment(2)
I'm writing modules for reusing them in several angular apps. Thats why I want to ship enums within the module.Bianco
Look. When you will add your modules in the packages of an application, you can export it from the barrel file of your package. It may contains for example export yourModule from yourFile; export yourEnum from yourEnumFile and then get your module and enum like import { YourModule, YourEnum } from YourPackage;Knockknee

© 2022 - 2024 — McMap. All rights reserved.