如何在另一个模块/路由器中使用组件

时间:2018-02-28 16:14:30

标签: angular module components

我尝试使用其他模块中的其他组件,但它在我的路由器插座中无效。

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

我的问题是,当我尝试在product.component.html中调用键盘组件时,它会给我一个错误,表明它不存在。但是,当我在main.component.html中调用它时,它可以正常工作。

1 个答案:

答案 0 :(得分:1)

如果您的组件应由app模块和主模块使用,则应该在主模块或其他共享模块中。以下示例显示了如何使用共享模块。

AppModule声明

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

MainModule声明

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

SharedModule声明

@NgModule({
  imports: [ CommonModule ],
  declarations: [ KeypadComponent ],
  exports: [ KeypadComponent ]
})
export class SharedModule { }
相关问题