You can use a ViewChild to reference the template content and then pass it to the component outlet using createEmbeddedView and attach.
import { Component, ViewChild, AfterViewInit, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
template: `<ng-content></ng-content>`,
})
export class MyComp {}
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule],
template: `
<div #container></div>
`,
})
export class App implements AfterViewInit {
@ViewChild('container', { read: ViewContainerRef, static: true }) container: ViewContainerRef;
constructor(private cfr: ComponentFactoryResolver) {}
ngAfterViewInit() {
const factory = this.cfr.resolveComponentFactory(MyComp);
const componentRef = this.container.createComponent(factory);
const templateRef = this.container.createEmbeddedView(this.ref.nativeElement);
componentRef.instance.viewRef = templateRef;
componentRef.changeDetectorRef.detectChanges();
this.container.detach();
}
}
ViewChild to get a reference to the ViewContainerRef of the div with the #container template variable. Then, in the ngAfterViewInit lifecycle hook, we create a component factory for MyComp and use it to create a new instance of the component. We also create an embedded view of the content defined by the #ref template variable using createEmbeddedView, and attach it to the component instance using instance.viewRef.
hope it's helps ..!