I went to the official angular documentation to learn about this, but it was way too complex. So I’m going to demonstrate the use of Dynamic Component Loading/ Injection in Angular.
I have a login form, when I click the remember me checkbox, the “You’ll be logged in for xx days” message should be shown.
In the previous blogs, I have demonstrated the exact scenario. but this time, I’m going to do that little different. The message itself will be in the AuthMessage Component. so based on the rememberme checkbox value, I’m going to show/hide the component.
In the above code,
I am showing/hiding the app-auth-message component based on the showMessage value. The real problem is, even if the value is false and the component is not needed, this component is loaded initially. Lets say, we have 20 components, and based on the condition only 1 is needed, the remaining 19 components is compiled and loaded initially. This will compromise the performance of the app overtime. For this purpose, we need to load components dynamically.
In the above code, I have an empty ng-template which acts a container to hold the component.
In the above code, first I need to manipulate the dom element, for that I have used ViewChild and ViewContainerRef.
“entry” in component.ts file actually refers to the ng-template in the html file.
It is to be noted that, we need to first create a factory to hold the component and then inject that factory to the dom element.
const authMessageFactory = this.resolver.resolveComponentFactory(AuthMessageComponent);
The above code will create a factory resolver to a particular component.
The above piece of code, will actually create a component from the factory and inject in to the dom element.
You can get the code from my repository