【问题标题】:How to use component in a in another module/router如何在另一个模块/路由器中使用组件
【发布时间】:2018-08-08 14:14:10
【问题描述】:

我正在尝试使用另一个模块中的另一个组件,但它在我的路由器插座中不起作用。

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

ma​​in.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 中调用它时,它工作正常。

【问题讨论】:

  • 您的键盘组件未在任何模块中声明。如果你想在其他模块中重用它,你应该导出它。
  • 哦,对不起,是的。我提供了文件的另一个版本,这样我就可以指出问题的重点。
  • 我已经看过它似乎不起作用
  • 如果键盘组件只需要被 MainModule 访问,将它移到那里而不是 AppModule。如果两者都需要使用,请将其移至共享模块。如果您对后面的方法感兴趣,请告诉我,我会发布一些示例代码。

标签: angular module components


【解决方案1】:

如果你的组件应该被应用模块和主模块使用,它应该放在主模块或另一个共享模块中。以下示例展示了如何使用共享模块。

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

【讨论】:

    猜你喜欢
    • 2020-05-31
    • 1970-01-01
    • 2023-03-20
    • 2020-10-28
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2018-06-15
    • 2018-10-31
    相关资源
    最近更新 更多