为什么延迟加载模块必须导入 commonModule? Angular 2
why lazy loaded module has to import commonModule? Angular 2
当我们在应用程序的根模块中导入 BrowserModule 时,我们可以使用 NgIf 和 NgFor(在预加载组件中)。但是对于延迟加载的模块,我必须导入 CommonModule ,它已经由 root 的 BrowserModule 导出。那么为什么我们必须在延迟加载模块中再次导入它?
浏览器模块用在应用程序的根模块中,当我们使用模块时,导入特定于模块。
当使用功能模块延迟加载组件时,我们必须在功能模块中导入公共模块,以便告诉 Angular 包含一些内置指令(如 ngFor 和 ngIf)的浏览器模块也可以在功能模块中使用.
请记住,浏览器模块的导入只会在 app.module 中使用一次,而我们想要在我们的功能或共享模块中使用这些内置指令的其他地方我们需要导入通用模块.
正如 Ward Bell 所说(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
模块不继承对其他模块中声明的组件、指令或管道的访问。(https://angular.io/guide/ngmodule#add-the-contactmodule 见橙色块)
这就是为什么您必须导入 CommonModule
才能访问 ngIf
、ngFor
等指令。您的模块对来自其他模块的指令一无所知。它只查看导入模块 declarations
和 exports
另请参阅:
当我们在应用程序的根模块中导入 BrowserModule 时,我们可以使用 NgIf 和 NgFor(在预加载组件中)。但是对于延迟加载的模块,我必须导入 CommonModule ,它已经由 root 的 BrowserModule 导出。那么为什么我们必须在延迟加载模块中再次导入它?
浏览器模块用在应用程序的根模块中,当我们使用模块时,导入特定于模块。 当使用功能模块延迟加载组件时,我们必须在功能模块中导入公共模块,以便告诉 Angular 包含一些内置指令(如 ngFor 和 ngIf)的浏览器模块也可以在功能模块中使用.
请记住,浏览器模块的导入只会在 app.module 中使用一次,而我们想要在我们的功能或共享模块中使用这些内置指令的其他地方我们需要导入通用模块.
正如 Ward Bell 所说(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
模块不继承对其他模块中声明的组件、指令或管道的访问。(https://angular.io/guide/ngmodule#add-the-contactmodule 见橙色块)
这就是为什么您必须导入 CommonModule
才能访问 ngIf
、ngFor
等指令。您的模块对来自其他模块的指令一无所知。它只查看导入模块 declarations
和 exports
另请参阅: