2

I have learnt that we can lazy load modules in an angular 2 application. But similarly is it possible to lazy load simply a component(instead of wrapping it in a module) : https://angular.io/docs/ts/latest/guide/ngmodule.html#!#lazy-load

Edit How to share resources like Components, Directives and Services between the main module and lazily loaded module?

jackOfAll
  • 2,350
  • 4
  • 18
  • 38

1 Answers1

3

No, only modules are supported to be lazy loaded.

Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
  • Why can't we do that with a module loader like systemJs or maybe requireJs? – Vineet 'DEVIN' Dev Dec 27 '16 at 10:22
  • 1
    Why would you want to? One of the main points of `@NgModule` is to make lazy loading work with all bundlers. If you want to lazy load a single component, than make a module that only contains that component. – Günter Zöchbauer Dec 27 '16 at 10:23
  • Isn't creating a module every tiny reusable component like a small widget an overhead though? – jackOfAll Dec 27 '16 at 10:41
  • 1
    Sure it's an overhead. Why do you think you need to lazy load a small widget on its own? – Günter Zöchbauer Dec 27 '16 at 10:43
  • 1
    In case I need to include that widget in two separate lazily loaded views. – jackOfAll Dec 27 '16 at 11:39
  • I have edited my question If you could clarify the new Edit it will be great. – jackOfAll Dec 27 '16 at 11:47
  • @GünterZöchbauer : Quoting above edit - How to load modules that are dependent on previously loaded module? Also, say I am making a multiple page web app, and each page is a module, I want to load that page as a module(for lazy loading) on a particular route. How would I declare that route and if that page is dependent on a service of parent module then how to use that service? How to write code for this situation which will work in both dev and after AoT compilation for prod? – Vineet 'DEVIN' Dev Dec 27 '16 at 11:52
  • "How to load modules that are dependent on previously loaded module?" I don't understand what you mean by that. When you add modules to imports of other modules, then the imported module will be loaded when the importing module is loaded. When the imported module was already loaded by another eager or lazy loaded module it won't be loaded again but instead the already loaded will just be reused. – Günter Zöchbauer Dec 27 '16 at 12:03
  • What do you mean by "Also, say I am making a multiple page web app". Angular is for single page applications (SPA). – Günter Zöchbauer Dec 27 '16 at 12:04
  • Okay, let me put it this way. Angular team gives a hero app in tutorial. It has 3 routes described in it - dashboard, heroes and hero details. Now I want to load hero details component in browser only when the user navigates to '/hero/:id'. 1st qn - How to import a new module for this and How should I declare my routes now? 2nd qn - How to share services of app module in this new module? – Vineet 'DEVIN' Dev Dec 27 '16 at 12:27