Angular 15: Difficulty with Dynamic Component Injection and Lifecycle Hooks
I'm performance testing and I'm working on a personal project and I'm facing an issue with dynamically injecting components in Angular 15 and properly handling their lifecycle hooks. I have a scenario where I need to load a component based on user interaction, but I'm noticing that the lifecycle hooks are not being invoked as expected. Iโm using the `ComponentFactoryResolver` for dynamic component creation in a parent component. Hereโs a simplified version of my code: ```typescript import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, OnInit } from '@angular/core'; import { DynamicComponent } from './dynamic.component'; @Component({ selector: 'app-parent', template: `<ng-template #dynamicComponentContainer></ng-template>` }) export class ParentComponent implements OnInit { @ViewChild('dynamicComponentContainer', { read: ViewContainerRef, static: true }) dynamicComponentContainer!: ViewContainerRef; constructor(private componentFactoryResolver: ComponentFactoryResolver) {} ngOnInit() { this.loadComponent(); } loadComponent() { const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent); const componentRef = this.dynamicComponentContainer.createComponent(componentFactory); componentRef.instance.someInput = 'Hello'; componentRef.changeDetectorRef.detectChanges(); } } ``` And here is the `DynamicComponent`: ```typescript import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-dynamic', template: `<div>{{ someInput }}</div>` }) export class DynamicComponent implements OnInit { @Input() someInput!: string; ngOnInit() { console.log('DynamicComponent initialized with input:', this.someInput); } } ``` The issue I'm encountering is that the `ngOnInit` method in `DynamicComponent` is not being called when I dynamically create the component. Iโve verified that the input is being set, but the initialization is skipped. Iโve tried adding `componentRef.changeDetectorRef.detectChanges()` after creating the component, but it didn't help. Any insights on what I might be missing or how to ensure the lifecycle hooks trigger correctly? I'm working on a web app that needs to handle this. Is there a better approach? Any help would be greatly appreciated!