简体   繁体   中英

How to use component in a in another module/router

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.

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 { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM