why lazy loaded module has to import commonModule? Angular 2

后端 未结 2 1197
你的背包
你的背包 2020-12-03 08:11

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 i

相关标签:
2条回答
  • 2020-12-03 08:32

    The Browser module is used in the root module of the app and when we are using modules the imports are specific to the modules. When using feature modules for lazy loading components we have to import common module in the feature module, so as to tell Angular that the browser modules whixh contains some build in directives like ngFor and ngIf to be available in the feature module too.

    Remember that the import for browser module will be only used only once in the app.module and where ever else we want to use these built in directives in our feature or shared modules we need to import the common module.

    0 讨论(0)
  • 2020-12-03 08:47

    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
    0 讨论(0)
提交回复
热议问题