14

I have RoomsComponent in the AppModule, its route is /rooms. Also i have a lazy-loaded module CompaniesModule with component CompaniesComponent with the route /companies.

I'm trying to build a route like /companies/{company_id}/rooms/ when RoomsComponent is reused from AppModule.

I can't do it a long RoomsComponent is not declared in the CompaniesModule, but this throws me an error, because a component cannot be declared in multiple modules.

sandum
  • 751
  • 5
  • 13
  • 25
  • See https://stackoverflow.com/questions/39601784/angular-2-use-component-from-another-module/39601837#39601837 – yurzui Sep 23 '17 at 06:53

1 Answers1

47

Declare the RoomsComponent in a Shared module and then import that shared module into the modules that need it. Here is an example of one of my Shared Modules:

import { NgModule }  from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { StarComponent } from './star.component';

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

Notice that my StarComponent is declared AND exported here. It can then be used in any component that is declared in a module that imports this shared module.

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • 1
    Ok, but how to use that component in another module if we don't declare it? – sandum Jul 04 '17 at 12:00
  • 1
    If it's declared in a module that exports it ... and we import that module ... that's all we need. See this video for more information on modules : https://www.youtube.com/watch?v=ntJ-P-Cvo7o&t=2s – DeborahK Jul 04 '17 at 14:51
  • Or the Angular docs here: https://angular.io/guide/ngmodule#shared-modules – DeborahK Jul 04 '17 at 14:52
  • 1
    I also have a sample app here that demonstrates shared modules : https://github.com/DeborahK/Angular2-GettingStarted – DeborahK Jul 04 '17 at 14:54
  • 1
    How you do it if Star is another big component, and you don't wanna put it in SharedModule because you use `LazyLoad`? – Gaspar Oct 04 '18 at 19:00
  • If the Star is to be shared, it should not be in another component. It should be its own component. And lazy loading should not affect it? – DeborahK Oct 08 '18 at 18:54
  • Exporting the modules from Shared Module means that anything that imports Shared Module will automatically have access to CommonModule and FormsModule so you don't have to repeat importing each one. Did you check about the youtube video referenced in the second comment above? – DeborahK Feb 10 '19 at 09:26