1

I've an Angular 2 component, which contains multiple sub-components. For a few of them it's quite expensive to load them and sometimes it is not necessary to load them at all. For example if the user is not scrolling that far.

Anyway, I know how I can lazy load routes, but is there a way of lazy loading a template? Like only if a element is in or close to the Viewport?

tschaka1904
  • 1,303
  • 2
  • 17
  • 39

2 Answers2

1

There is no way to lazy load templates. What you can do is to lazy load modules. How to manually lazy load a module?

If you use this with ViewContainerRef.createComponent() (see Angular 2 dynamic tabs with user-click chosen components for an example) to dynamically add the components that you only want to show if the users scrolls far enough, it might work (not tried myself yet).

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Okay. Thanks! Might be a different question, but how about loading a component once everything else is loaded? Kind of forcing the component to wait until all the others are loaded. – tschaka1904 Nov 04 '16 at 12:24
  • I guess a simple `` or `` is the simplest and most efficient way. What `isAllLoaded` means exactly needs to be defined though. – Günter Zöchbauer Nov 04 '16 at 12:27
0

You can segregate or group sub-components to be displayed into smaller components to be loaded together. To reduce the time to load, 1. try to use smaller templates inline into component file. 2. Use *ngIf directive in your template which can avoid rendering of the template and component instance is not created as such. However, take note that if you're using *ngIf it is better to use only is the DOM is not refreshed fequently, else you may create DOM and use the component by binding it with [hidden] attribute of the DOM

Ashwin Kumar
  • 711
  • 5
  • 6