Posted onEdited onInangular Symbols count in article: 544Reading time ≈2 mins.
Introduction
In this article, we will learn how to dynamically load a component in Angular, In addition to load a component in html template directly, you can also load a component dynamically with NgComponentOutlet or ViewContainerRef
NgComponentOutlet
NgComponentOutlet is a directive that provide a declarative way for dynamic component creation, it requires a component type as input and create an instance of the component in the view.
1
*ngComponentOutlet="componentType"
Here are the code snippets to dynamically load a component with NgComponentOutlet:
// We return the component type by condition. getComponent() { returnthis.showProduct? ProductComponent: CustomerComponent; } }
Question: What’s the difference between *ngComponentOutlet and *ngIf* in this case? *ngIf can also load the component by condition.
ViewContainerRef
ViewContainerRef is a class that represents a container where one or more views can be attached to a component. It provides methods to create components and attach them to the container.
Explanation: The above code decides which component should be loaded when the user clicks the button, based on the showProduct variable. After running the program, press F12 to open the developer tools, and observe the Network tab. You can see that after clicking the Lazy load component button, the app initiates a request to dynamically load the Product component.
The component was bundled separately with name chunk-VFVWUJZL.js to support lazy load, if you want to see the real name of the chunk file, you can add namedChunk to your angular.json file.
In this way the chunk file will got a name like product.component-RGAR2EGQ.js
Finally, the getComponent method can be optimized to avoid duplicate code, but it seems that the readability is not very good after optimization. What do you think?