Angular 15 - Issue with Dynamic Component Rendering Not Binding Inputs Correctly
This might be a silly question, but I'm facing a challenge with dynamically rendering components in Angular 15... I have a scenario where I'm trying to load a component dynamically based on user selection and pass input data to it. However, the inputs in the dynamically loaded component are not being bound correctly. Here's a simplified version of what I'm doing: In my main component, I have a method to load the desired component: ```typescript import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core'; import { MyDynamicComponent } from './my-dynamic.component'; @Component({ selector: 'app-main', template: `<ng-container #dynamicContainer></ng-container>`, }) export class MainComponent { @ViewChild('dynamicContainer', { read: ViewContainerRef, static: true }) dynamicContainer!: ViewContainerRef; constructor(private resolver: ComponentFactoryResolver) {} loadComponent(data: any) { const componentFactory = this.resolver.resolveComponentFactory(MyDynamicComponent); const componentRef = this.dynamicContainer.createComponent(componentFactory); componentRef.instance.inputData = data; } } ``` And in `MyDynamicComponent`, I have an input property: ```typescript import { Component, Input } from '@angular/core'; @Component({ selector: 'my-dynamic', template: `<div>{{ inputData }}</div>`, }) export class MyDynamicComponent { @Input() inputData!: any; } ``` When I call `loadComponent` with some data, the `inputData` in `MyDynamicComponent` is not displaying correctly. Instead of showing the passed value, it renders as `undefined`. I've checked that the `loadComponent` method is being invoked correctly, and the `data` passed to it is indeed valid. I've tried using `ChangeDetectorRef` to force change detection, but that didn't help either. ```typescript import { ChangeDetectorRef } from '@angular/core'; constructor(private resolver: ComponentFactoryResolver, private cdr: ChangeDetectorRef) {} loadComponent(data: any) { const componentFactory = this.resolver.resolveComponentFactory(MyDynamicComponent); const componentRef = this.dynamicContainer.createComponent(componentFactory); componentRef.instance.inputData = data; this.cdr.detectChanges(); // still doesn't work } ``` Is there something I'm missing in the lifecycle of the component or in the way I'm passing data? Any suggestions would be greatly appreciated! I've been using Typescript for about a year now. Any advice would be much appreciated. Could this be a known issue?