1

I'm trying to use another component from another module, but its not working in my router-outlet.

app.module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MainModule } from './main/main.module';
import { AppComponent } from './app/app.component';
import { KeypadComponent } from './keypad/keypad.component;
import { routing } from './app.routing';

@NgModule({
  declarations: [
    AppComponent,
    MainComponent,
    KeypadComponent
  ],
  imports: [
    BrowserModule,
    CommonModule,
    MainModule,
    routing
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

main.module

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

import { ProductComponent } from './product/product.component';

@NgModule({
  imports: [
    routing
  ],
  declarations: [ProductComponent]
})
export class MainModule { }

My issue is that when I try to call the Keypad Component in product.component.html, it will give me an error that says it does not exist. However, when I call it in my main.component.html, it works fine.

Eric Chu
  • 1,649
  • 3
  • 20
  • 26
  • 1
    your keypad component isn't declared in any module. And you should export it if you want to reuse it in another modules. – JEY Feb 28 '18 at 16:17
  • Oh sorry, it is. I gave another version of the files so I can show the focus of whats wrong. – Eric Chu Feb 28 '18 at 16:20
  • Possible duplicate of [Angular 2 Use component from another module](https://stackoverflow.com/questions/39601784/angular-2-use-component-from-another-module) – Bunyamin Coskuner Feb 28 '18 at 16:55
  • I've looked at that already it didn't seem to work – Eric Chu Feb 28 '18 at 17:11
  • If the Keyboard component only needs to be accessed by the MainModule, move it in there instead of AppModule. If it needs to be used by both, move it to a shared module. If you are interested in the later approach, let me know and I'll post some sample code. – DeborahK Feb 28 '18 at 17:44
  • Yes please I need to know how to use it in a shared module. – Eric Chu Feb 28 '18 at 18:51

1 Answers1

2

If your component should be used by app module and main module it should go in the main module or in another shared module. Following example show how to use a shared module.

AppModule declaration

@NgModule({
  declarations: [
    AppComponent,
    MainComponent,
  ],
  imports: [
    CommonModule,
    MainModule,
    SharedModule,
    routing
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

MainModule declaration

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

SharedModule declaration

@NgModule({
  imports: [ CommonModule ],
  declarations: [ KeypadComponent ],
  exports: [ KeypadComponent ]
})
export class SharedModule { }
JEY
  • 6,973
  • 1
  • 36
  • 51