The template of a component will not always be fixed. Your app might need to load some new components during runtime.
Usage Scenarios:
1. Page loading loads different components according to different parameters, showing different effects 2. The page is composed of multiple elements, not all of them need to be displayed at the beginning, and specific information will be displayed after the user clicks, such as: tab tabs, dynamic pop-up modal boxes, etc.
The usage scenario of this article is 2, just imagine,If you don't use dynamic loading, when you open the main interface, all the hidden components of the page will be loaded, and all components call their corresponding interface services, often, we don't need to see all the information, which is a great waste of resources, and may also cause the main interface to load slowly, affecting the user experience。
There are two ways to dynamically load components in ng:
Load already declared components: Use ComponentFactoryResolver to render an instance of a component to another component view; Create and load components dynamically: Use ComponentFactory and Compiler to create and render components According to our needs, the individual components are developed in advance and need to be displayed on the same component. So the first way meets our requirements.
To dynamically load components using ComponentFactoryResolver, you need to understand the following concepts:
- ViewChild: Property decorator, through which you can get the corresponding elements on the view;
- ViewContainerRef: A view container on which components can be created and deleted;
- ComponentFactoryResolver: A component parser that can render one component on a view of another.
First, let's look at the renderings, click the modal1 button to dynamically load the modal1 component, and click the modal2 button to dynamically load the modal2 component.
First, we create an angular project.
Create 4 components, namely index, modal1, modal2, and modal3, of which modal1 and modal2 are our dynamically loaded components.
index component
html:
ts:
modal1 component
html:
ts:
modal2 component
html:
ts:
modal3 component
html:
ts:
We printed their names on the constructor for 3 modals.
modal1 and modal2 are both dynamically loaded, only when the button is clicked to load, the execution constructor will be triggered, modal3 does not use dynamic loading, after the parent interface is loaded, the modal3 interface constructor will be executed immediately.
In this way, you can see the advantages of dynamic loading, and it will not load if you don't use it, similar to lazy loading in C#.
Source code download:
Tourists, if you want to see the hidden content of this post, please Reply
Resources:The hyperlink login is visible.
|