Engineering/Coding Standards/TypeScript/Angular/Angular Modules/

Angular Modules Standards · NG-03

Shared

Include a SharedModule · NG-03.1 · MUST

Include a SharedModule for application-wide pipes, directives etc.

Include a CommonModule · NG-03.2 · SHOULD

The SharedModule should also contain CommonModule and either FormsModule (from @angular/common) or ReactiveFormsModule (from @angular/forms).

Features

Feature modules must share their name with its parent directory · NG-03.3 · MUST

Feature modules must be placed in a folder that is the same name as the feature it is for, eg users.

Feature modules should have their own routing module · NG-03.4 · SHOULD

Feature modules must be used and should have their own routing module, to use lazy loading easily.

In addition to a feature module, if there is anything from a feature area that needs to be used by other module, use a FeatureSharedModule.

Core Module

Include a CoreModule · NG-03.5 · MUST

Include a CoreModule that contains all single use classes (interceptors/etc). This should be imported in your AppModule only.

It separates this logic away from your AppModule.

Single use components should be declared in the CoreModule · NG-03.6 · SHOULD

Any single use components (for example, navigation) should be declared in the CoreModule, not the AppModule. This is the whole purpose of the CoreModule, offsetting from the AppModule.

Use providedIn over adding them to the providers array · NG-03.7 · SHOULD

In most cases you should use providedIn: ‘root’ for services instead of adding them to the providers array of a Module.

This means that you don’t have unnecessary imports. providedIn: ‘root’ makes the service available to the whole app anyway.

If the service is only needed by a certain feature module then you should not use providedIn: ‘root’ and should instead add the service to the provider array for that feature module.

Avoid re-importing single use modules · NG-03.8 · MUST

Re-importing of single use modules must be prevented.

Modules such as the CoreModule must only be imported once, importing them any more than that will cause problems.

...

@NgModule({...})
export class CoreModule {
    constructor(
        @Optional()
        @SkipSelf()
        core?: CoreModule
    ) {
        if (core) {
            throw new Error('Core injected more than once');
        }
    }
}