I have a problem where I have a module called CoreModule
and it is imported in the AppModule
and I am trying to use this module in some child module but if I import the module in the child module it gives this error CoreModule has already been loaded. Import Core modules in the AppModule only.
when I go to the some component in that module.
If I don't import the CoreModule
in child module it gives this error:Can't bind to 'ngxHasAnyRole' since it isn't a known property of 'button'
imports in my AppModule
looks like this
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
AppRoutingModule,
NbSidebarModule.forRoot(),
NbMenuModule.forRoot(),
NbDatepickerModule.forRoot(),
NbDialogModule.forRoot(),
NbWindowModule.forRoot(),
NbToastrModule.forRoot(),
CoreModule.forRoot(),
ThemeModule.forRoot(),
LoggerModule.forRoot({
level: NgxLoggerLevel.INFO,
enableSourceMaps: true
}),
],
My CoreModule
look like this
...
@NgModule({
imports: [
CommonModule,
],
exports: [
NbAuthModule,
HasRoleDirective,
HasAnyRoleDirective,
],
declarations: [HasAnyRoleDirective, HasRoleDirective],
})
export class CoreModule {
constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
throwIfAlreadyLoaded(parentModule, 'CoreModule');
}
static forRoot(): ModuleWithProviders<CoreModule> {
return {
ngModule: CoreModule,
providers: [
...NB_CORE_PROVIDERS,
],
};
}
This is the part of the html where I try to use directive from CoreModule
<button nbButton
(click)="new()"
[ngxHasAnyRole]="['ROLE_TEST', 'ROLE_ADMIN']"
class="table-button"
status="primary"
size="small">
NEW
<nb-icon icon="plus-outline"></nb-icon>
</button>
I don't want to import in the child module as this is imported in the Parent module. How can I fix this problem?
Additional info
When I do ng serve
while having CoreModule
imported in the child and then delete it while ng serve
is on. It works but if I close and start again. It won't start.
A CoreModule
should be used for things that should only be imported once. These are usually imports from app wide services. What should definitely not go in a CoreModule
are components, directives and pipes.
These are things that should go in a SharedModule
.
There are several NgModule categories declared by angular, which you can use as a guideline:
My advice is to really read the excellent docs/guides provided on angular.io
So what do you have to do? Remove the export and declarations of HasAnyRoleDirective
and HasRoleDirective
from your CoreModule
and place these in a SharedModule
or create a small module RoleModule
and only import this where necessary. Up to you