5

I'm Angular2 newbie and I have some difficulties with im(ex)porting modules.

According to official styleguide CoreModule is:

CoreModule - import once when the app starts and never import anywhere else.

Does this mean that all those exported stuff from Core module will be only available in the Module where it is imported only? There is no way to make those stuff available in some child module? I created dummy project just to test this behavior:

Dummy component:

@Component({
  selector: 'dummy-component',
  template: '<h4>Dummy component</h4>',
})
export class DummyComponent {}

Core module:

import { DummyComponent } from './dummy.component';

@NgModule({
  declarations : [DummyComponent],
  exports : [DummyComponent]
})

export class CoreModule {}

App module(root module):

@NgModule({
  declarations: [AppComponent,],
  imports: [BrowserModule, CoreModule, HomeModule, RoutingModule],
  exports : [CoreModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Home module declares home component:

@Component({
  selector: 'home-component',
  template: 
  `
    <h2>Home component</h2>
    <dummy-component></dummy-component>
  `
})
export class HomeComponent {}

When I try to run this code I got this error:

'dummy-component' is not a known element

1 Answer 1

8

If you want stuff in other modules, then put it into a shared module (feature module). CoreModule is not the right place.

Yes you need to import a module to every module where you want to use components, directives, or pipes from that module.

Sign up to request clarification or add additional context in comments.

4 Comments

What if you have a root-level service that uses a component? where should that component be declared? imagine you have a snackbar service that uses a component, you want to reuse the service all across your application.
A service shouldn't use a component. Components use services. Add a snackbar component that injects the service and subscribes to an observable provided by the service.
where would you place such component if it is to be reused across the application? also what kind of observable the snackbar component is subscribing to, can you be a little more specific?
Place the component as direct child of AppComponent so that it's always loaded. Every part of your app that wants to use the component injects the service. The service provides a method like "showMessage(msg:string)` that when called emits a value to the observable the snackbar component subscribes to. Sorry, I do not have more concrete information at hand. It's a while I worked with Angular. There should be plenty of examples out there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.