Home > OS >  What is the use case for dynamic component loading?
What is the use case for dynamic component loading?

Time:02-14

I am having a little trouble understanding what the use case is for dynamic component loading. The explanation from the ng docs states:

An application might need to load new components at runtime.

Could you not handle this scenario with an ngSwtich that then loads a child-component? Or is the use case for components that are not even bundled with the app that can be loaded dynamically at runtime? So in this case the component is run through the Angular compiler at runtime and compiles the component dynamically, then injecting the compiled component into the running application, or?

Aside from the technical side of this, when would this be necessary? Don't you normally have dynamic data feeding a component rather than having dynamic components inserted into a dom node? Maybe I am just lacking creativity, but I can not see when dynamically loading a component would be necessary.

CodePudding user response:

Component "loading" (as the term is used on that page) refers to the creation of a component instance within an identified area of the DOM (the ViewContainer).

Component loading is static if the decision to create the component is made at build time (by mentioning the component in a template to be compiled). Component loading is dynamic if the decision to create the component is made at runtime (by telling a ViewContainer to create a particular component).

Dynamic component loading is used by structural directives such as ngIf, ngSwitch, ngFor, router-outlet, ..., to conditionally select the type or number of components to create, as well as manage their lifetime.

In describing how these components manage that feat, the documentation empowers us to write our own structural directives should the default directives prove inadequate for our needs.

For instance, imagine router-outlet had not been invented yet. You could work around this by having one huge ngSwitch instead, but you probably agree that router-outlet is more convenient to use. Having seen the need for such specialized components, the angular team opted to give us the means to write them.

PS: I agree that dynamic component "loading" is a misleading phrase, because one naturally thinks about loading code from the server, which is a wholly different beast. Of course, it is possible to combine dynamic component creation with dynamic code loading, as the lazy routes feature of the router demonstrates, but it quite possible, and normal, to use dynamic components without dynamic code loading.

  • Related