Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using component from another module in Angular 4

Tags:

angular

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.

like image 686
sandum Avatar asked Jul 04 '17 08:07

sandum


People also ask

How do I use a component from another module?

Component can be declared in a single module only. In order to use a component from another module, you need to do two simple tasks: Export the component in the other module. Import the other module, into the current module.

Can we use same component in different modules?

You can use same directives/components in multiple modules without errors.


1 Answers

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.

like image 53
DeborahK Avatar answered Sep 27 '22 21:09

DeborahK