Hello guys how are you? Welcome back on my blog Therichpost. Today in this post I am going to share In Angular how to pass a component as a value in an object by referring to the component’s class?
Angular 19 came. If you are new then you must check below two links:
Now guys here is the complete code snippet and please follow carefully:
In Angular, you can pass a component as a value in an object by referring to the component’s class. Later, you can dynamically load the component using Angular’s ComponentFactoryResolver
or the ViewContainerRef
API.
Here’s a step-by-step example:
Step 1: Create Components
Create the components you want to pass in the object.
// component-a.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-component-a', template: `<p>Component A</p>`, }) export class ComponentAComponent {}
// component-b.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-component-b', template: `<p>Component B</p>`, }) export class ComponentBComponent {}
Step 2: Define an Object with Component References
In your parent component or a service, create an object where components are stored as values.
// component-map.ts import { ComponentAComponent } from './component-a.component'; import { ComponentBComponent } from './component-b.component'; export const ComponentMap = { componentA: ComponentAComponent, componentB: ComponentBComponent, };
Step 3: Load Components Dynamically
Use Angular’s ViewContainerRef
and ComponentFactoryResolver
to load the component dynamically.
Parent Component
import { Component, ViewChild, ViewContainerRef } from '@angular/core'; import { ComponentMap } from './component-map'; @Component({ selector: 'app-dynamic-loader', template: `<ng-container #dynamicContainer></ng-container> <button (click)="loadComponent('componentA')">Load Component A</button> <button (click)="loadComponent('componentB')">Load Component B</button>`, }) export class DynamicLoaderComponent { @ViewChild('dynamicContainer', { read: ViewContainerRef, static: true }) dynamicContainer!: ViewContainerRef; loadComponent(componentKey: string) { const component = ComponentMap[componentKey]; this.dynamicContainer.clear(); this.dynamicContainer.createComponent(component); } }
Explanation
- Component Map: The
ComponentMap
object holds references to components. - Dynamic Loading: Use
ViewContainerRef.createComponent()
to dynamically create and insert the component into the view.
Benefits
- This approach lets you use a central mapping of component keys to their corresponding components.
- It’s modular and scalable, making it easy to add new components to the map.
Let me know or comment below if you’d like a more detailed explanation or a working example!
Ajay
Thanks