How to Load Your Component Dynamically in Angular Application

Why we need dynamic component?

In Application sometimes you need to run your Component in the runtime, Which it means without using your selector can display the component based on your required logic condition, For that purpose you can load your component dynamically.

How does the dynamic component work?

Once we clear about why we need dynamic component, Next is to think how dynamic component works, In Angular every newly created component will be set or stored on the one factory, In Dynamic component we have to load manually in order to display your component, Just follow the example steps to see how dynamic component works

Steps to works for Dynamic Component

Here we have taken example on click button display name there is an two button, The button one name was khaleesi and another button name was Aryastark,

1_SOSsTTajBwazJO4sRnmKSw.png

When i click the khaleesi button it will displays Hello Khaleesi and when i click Aryastark button it will display as Hi AryaStark by dynamically

STEP 1: Create one Component.

STEP 2: Create Directive and Import ViewContainerRef

rt.png

With help of ViewContaineRef you can able to view the component.

STEP 3: Create two component in the single component. Here i have taken hellocomponent and hicomponent

hell.png

STEP 4: Import all your component and directive in app.module.

STEP 5: Create an entry component in app.module, Place your component.

app.mod.png

STEP 6: From the dynamic.component.ts import Hellocomponent.ts & Hicomponent.ts.

STEP 7: Add your directive through Viewchild and initialise your component in array.

1_Tul4rMcv0-SMU2wzwaeWag.png

STEP 8: Import the ComponentFactoryResolver and Initialise in the constructor

What is ComponentFactoryResolver ?

In Angular every created Component will be stored in the factor, These factors are created from the angular core, Here we manually gonna load the component in order to display the data.

STEP 9: Using the condition displaying the component in the view.

gf.png

STEP 10: From the dynamic.component.html, create the button and ng-template and add the directive selector

dy.png

Output :

op1.png

op2.png