Binabiko
Binabiko

Reputation: 47

Dynamic Component Loader vs. Lazy Loading

What is the difference between Dynamic Component Loader and Lazy Loading? I need to build an application that needs to have an <router-outlet> at the root of the application. My Problem is that I don't know how to implement a Component that renders Child-Components according to data, dynamically. My current approach builds up on Dynamic Component Loader, but using this technique I have issues concerning tracking my location, navigate back, etc. Is there any best practice for using "multiple <router-outlets>" (e.g. Lazy Loading)?

Thanks!

Upvotes: 2

Views: 1441

Answers (1)

rmcsharry
rmcsharry

Reputation: 5562

Loading components dynamically is not related to Lazy Loading.

Lazy Loading is a way to split up your application into modules that are loaded lazily (in the background) instead of loading your entire application at the start. This helps your app load more quickly so the first page is rendered sooner than it would if you did not use lazy loading.

For example, you might have a settings menu which loads various settings, but you don't expect users to visit that menu very often, so you put all the components for settings into a module and then you set that module to be loaded lazily (in other words none of that code needs to be downloaded unless a user actually visits the /settings route).

All angular applications must have a <router-outlet> at the base component (usually AppComponent). This is a requirement of all Angular applications.

You may want to consider also using auxiliary routes - these are optional, and allow you to load components in different 'places'. You can read about them here

Alternatively you can (for simple cases) just use ngIf, like this:

/app.component.html

<div *ngIf="isOption1(); else Option2">
  <my-option1-component></my-option1-component>
</div>
<ng-template #Option2>
  <my-option2-component></my-option2-component>
</ng-template>

/app.component.ts

public isOption1: boolean {
  return <some test that returns true or false>;
}

So based on the logic the method isOption1 returns, the user will see either Option1 component (when true) or the Option2 component (when false).

Upvotes: 2

Related Questions