Angular exported component from module not useable in another module

回眸只為那壹抹淺笑 提交于 2020-08-23 03:07:09

问题


I am exporting a custom component in my AppModule but can not use it in another module, which is being imported in the AppModule. I thought exported components are visible globally?

I am trying to use the CalendarComponent with the selector 'app-calendar' in a component within the TestModule.

app.module.ts

@NgModule({
  declarations: [ ... ,
    CalendarComponent,
  ],
  imports: [ ... ,
    TestModule,
  ],
  exports: [ ...
    CalendarComponent,
  ],
  providers: [ ... ],
  bootstrap: [AppComponent]
})

test.module.ts

@NgModule({
  declarations: [ ... ,
    TestComponent
  ],
  imports: [ ... ],
  exports: [ ... ],
  providers: [ ... ]
})

test.component.html

<app-calendar></app-calendar>

Console throws the error that 'app-calendar' is not a known element (not part of the module)

What am I missing?


回答1:


Create CalendarModule or add Calendar component to your share module(depends on your architecture) like:

calendar.module.ts

@NgModule({
  declarations: [CalendarComponent],
  exports: [CalendarComponent]
})
export class CalendarModule {}

In AppModule remove CalendarComponent everywhere and import CalendarModule(or SharedModule) if some of declarations uses CalendarComponent

app.module.ts

@NgModule({
  declarations: [ ... ,
    CalendarComponent,  <== remove it
  ],
  imports: [
    TestModule,
    // import CalendarModule here if any of declarations above use CalendarComponent in their template
  ],
  exports: [ ...
    CalendarComponent,  // remove it
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

test.module.ts

@NgModule({
  declarations: [ ... ,
    TestComponent
  ],
  imports: [ 
    CalendarModule <=== add this, so TestComponent will be able to use CalenderComponent in its template
  ]
})
export class TestModule {}

For more details see

  • Angular 2 Use component from another module


来源:https://stackoverflow.com/questions/46381730/angular-exported-component-from-module-not-useable-in-another-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!