Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 access submodule component

I have an Angular2 application with submodules:

├───app (module)                                 
│   ├───authentication (module)                 
│   │   ├───components                  
│   │   │   ├───login                   
│   │   │   ├───sign-in                 
│   │   │   ├───sign-up                 
│   │   │   ├───socials-callback        
│   │   │   └───socials-sign-in         
│   │   ├───models                      
│   │   └───services                    
│   ├───components                      
│   │   └───nav-bar                     
│   ├───home (module)                           
│   ├───shared (module)                          
│   │   ├───components                    
│   │   │   └───search-dropdown         
│   │   └───services                    
│   └───user (module)                             
│       ├───models                      
│       └───services                     

Each components are declared in the module_name.module.ts file (of their module). Each modules files are imported in the app.module.ts file.

Here is my app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import ...

import { SharedModule }    from './shared/shared.module';

@NgModule({
  imports: [
    AppRoutingModule,
    ...
    SharedModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

My shared.module.ts file:

import { NgModule } from '@angular/core';
import ...

import { SearchDropdownComponent } from './components/search-dropdown/search-dropdown.component';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    SearchDropdownComponent
  ]
})
export class SharedModule { }

When I try to access to SearchDropdownComponent from a template of my app module, I have an error telling my that there is no component corresponding to it.

But when I add the SearchDropdownComponent import directly on my app.module.ts file, it works.

Isn't it possible to access to a component of a sub module? I am doing something wrong?

like image 214
Ben Avatar asked Dec 25 '22 00:12

Ben


1 Answers

To make a component available outside the module, add it the module's exports declaration.

import { NgModule } from '@angular/core';
import ...

import { SearchDropdownComponent } from './components/search-dropdown/search-dropdown.component';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    SearchDropdownComponent
  ],
  exports: [
    SearchDropdownComponent
  ]
})
export class SharedModule { }

API Reference: NgModule.exports

Also note that a component can belong to only one module.

like image 181
Ronald Zarīts Avatar answered Dec 28 '22 10:12

Ronald Zarīts