Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why lazy loaded module has to import commonModule? Angular 2

When we import BrowserModule in root module of application ,we can use NgIf and NgFor( in eagerly loaded component). But for lazy loaded modules I have to import CommonModule which has been exported by BrowserModule of root. SO why do we have to import it again in lazy loaded module?

like image 992
Vivek Avatar asked Apr 01 '17 05:04

Vivek


People also ask

What is needed to set up a lazy loaded feature module in Angular?

To lazy load Angular modules, use loadChildren (instead of component ) in your AppRoutingModule routes configuration as follows. content_copy const routes: Routes = [ { path: 'items', loadChildren: () => import('./items/items. module'). then(m => m.

Why would you use lazy loading modules in Angular app?

Lazy loading modules helps us decrease the startup time. With lazy loading our application does not need to load everything at once, it only needs to load what the user expects to see when the app first loads. Modules that are lazily loaded will only be loaded when the user navigates to their routes.

How are modules loaded lazily in Angular?

Angular app may have multiple modules based on the nature of the application. The root module or app module is created under /src/app. The lazy load of the modules can be done using the root routing module. This loads the modules lazily using loadChildren method.

What is CommonModule in Angular?

CommonModule is used to export all the basic Angular directives and pipes. It is re-exported when we import BrowserModule into our angular application, BrowserModule is automatically imported into our application when we create our Angular application using 'ng new' command.


1 Answers

As Ward Bell said(https://devchat.tv/adv-in-angular/119-aia-avoiding-common-pitfalls-in-angular2):

As long as you only have one module in your application and you threw everything in there, you were benefiting from the common module hiding inside the browser module. The minute you create a new module, lazy or not, any new module and you declare anything into it, that new module has a clean state. It has no knowledge of anything, Angular or anything. It’s any module, not a lazy module in which you declare something, you’re going to have to import everything that you actually need for any of the component you declared in it. That’s why you needed common module

Modules don't inherit access to the components, directives, or pipes that are declared in other modules. (https://angular.io/guide/ngmodule#add-the-contactmodule see orange block)

That's why you have to import CommonModule to have access to ngIf, ngFor and so on directives. Your module doesn't know anything about directives from other modules. It only looks at its declarations and exports from imported modules

See also:

  • Angular 2 Use component from another module
like image 128
yurzui Avatar answered Oct 27 '22 08:10

yurzui