What is a Component Factory in Angular?
A Component Factory in Angular is a mechanism that allows you to dynamically create instances of a component at runtime. It is primarily…
What is a Component Factory in Angular?
A Component Factory in Angular is a mechanism that allows you to dynamically create instances of a component at runtime. It is primarily used for dynamic component loading when you need to insert components into a view without defining them statically in the template.
Understanding Component Factory
A Component Factory (ComponentFactory<T>) is an Angular class that provides a way to:
- Create an instance of a component.
- Attach it to a view container (
ViewContainerRef). - Manage its lifecycle dynamically.
It was commonly used with ComponentFactoryResolver before Angular 9. However, with Angular Ivy (Angular 9+), ComponentFactoryResolver is no longer necessary.
ComponentFactory Example (Pre-Angular 9)
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
@Component({
selector: 'app-dynamic',
template: '<ng-template #container></ng-template>',
})
export class DynamicComponent {
@ViewChild('container', { read: ViewContainerRef, static: true }) container!: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {}
loadComponent(component: any) {
const factory = this.resolver.resolveComponentFactory(component);
this.container.clear();
this.container.createComponent(factory);
}
}
Modern Approach (Angular 9+)
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-dynamic',
template: '<ng-template #container></ng-template>',
})
export class DynamicComponent {
@ViewChild('container', { read: ViewContainerRef, static: true }) container!: ViewContainerRef;
loadComponent(component: any) {
this.container.clear();
this.container.createComponent(component);
}
}
When to Use it?
It is should be used at the following time.
- Loading Components Dynamically
- Lazy Loading Components
- Embedding Components in Runtime Containers
메타데이터
- post_id
- e2c79e0773fb
- slug
- what-is-a-component-factory-in-angular-e2c79e0773fb
- url
- https://medium.com/@ss.web/what-is-a-component-factory-in-angular-e2c79e0773fb
- canonical_url
- https://medium.com/@ss.web/what-is-a-component-factory-in-angular-e2c79e0773fb
- author_url
- https://medium.com/@ss.web
- status
- ok
- fetched_at
- 2026-06-12 07:40:50