简体   繁体   中英

What is the scope of an Angular module Import

If I have three modules

  1. AppModule
  2. SharedModule
  3. ItemModule

Inside the SharedModule I have a PaginatorComponent that is exported as follows:

shared.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { PaginatorComponent } from './paginator/paginator.component';

@NgModule({
  imports: [
      CommonModule
  ],
  declarations: [
      PaginatorComponent
  ],
  providers: [],
  exports: [
      PaginatorComponent
  ]
})
export class SharedModule { }

I then import the shared module into my AppModule using the lines

app.module.ts

import { SharedModule } from './shared/shared.module';

imports: [
      ...
      SharedModule,
      ...

Question; Should my third "ItemModule" automatically have access to the PaginatorComponent or do I need to import directly into the 3rd module? Currently I get a variation of the generic error:

Can't bind to 'totalItems' since it isn't a known property of 'app-paginator'.
1. If 'app-paginator' is an Angular component and it has 'totalItems' input, then verify that it is part of this module.

Many thanks.

The answer can be found at https://medium.com/@cyrilletuzi/understanding-angular-modules-ngmodule-and-their-scopes-81e4ed6f7407 thanks to @Rama

In short, the answer is

  1. If the module is imported for components, you'll need to import it in each module needing them;

  2. If the module is imported for services, you'll need to import it only once, in the first app module.

This is something I misunderstood when I started Angular 2+/

You need to re-import every component you use in every module.

With you example, if you need to use PaginatorComponent into your ItemModule , you will need to import SharedModule into your ItemModule to make it work. (because SharedModule exports PaginatorComponent)

This is not the case for services/providers. If you inject a service, every child component will be able to access it.

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