Dynamic Components Overview ● Dynamic is programming that is not defined or coded during the build time but is created or instantiated during runtime. ● Dynamic Components are not defined or used in any template across the application during the build time but are instantiated during the runtime. ● Dynamic Components doesn’t mean that we can just dynamically add a component from the internet during runtime, but it means that we dynamically render the component defined in the same project but is not used in the template into our application during the runtime. ● Dynamic Components are defined in the same project but are not used in any template and, when required during runtime, are used in the application. ● Let’s Understand Dynamic Component by creating a new Project: ○ Create a new project using Angular CLI ng new project_name ■ ○ ng new dynamic Create a new component using Angular CLI ng g c component_name or ng generate component component_name ■ ○ 1 ng g c dynamic This is how the app.module.ts looks like: ○ @ViewChild Decorator is used for interaction between components and provides a way to access and manipulate the elements, directives, and components in the DOM. ○ @ViewChild uses selector metadata to select an element to query, and this can be directive name or type. ○ @ViewChild uses another metadata read which is used to read different tokens from the elements that are queried. ○ ViewContainerRef represents a container where views can be attached to a component, and elements in DOM can be used as a view container. ○ It is used to insert new components or templates. ○ ComponentFactoryResolver is a simple registry that maps components to the generated component factory classes used to create instances of components. ○ ComponentFactoryResolver is used to obtain the factory for a given component type. ○ It then uses the factory’s create method to create a component of that type. app.component.ts: 2 ● We can add the ng-container directive to our app.component.html file, creating a placeholder to render our dynamic component and assign the id. ● <ng-container #container></ng-container> ● The template for the app component is as follow: ● The template for the dynamicComponent is as follow: ● <p>Dynamic Component </p> ● Now use the command ng serve to run the application. Now Clicking on the Dynamically Add Component Button, the content of our Dynamic Component are displayed on the screen. ● The content of the Dynamic Component was not used in any application template during build time, but we instantiated the component into the application during the runtime. 3