2

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?

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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.
I guess a simple <my-component *ngIf="isAllLoaded"></my-component> or <my-component *ngIf="someGlobalService.isAllLoaded"> is the simplest and most efficient way. What isAllLoaded means exactly needs to be defined though.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.