It seems like ComponentFactoryResolver is deprecated.
I am trying to render a portal in the body (outside the application context)
import {
AfterViewInit,
ApplicationRef,
Component,
ComponentFactoryResolver,
Injector,
} from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { SidebarComponent } from './sidebar/sidebar.component';
import { HeaderComponent } from './header/header.component';
import { MyFilesComponent } from './my-files/my-files.component';
import { TrashComponent } from './trash/trash.component';
import { ModalComponent } from './shared/modal/modal.component';
import { ComponentPortal, DomPortalOutlet } from '@angular/cdk/portal';
@Component({
selector: 'app-root',
standalone: true,
imports: [
RouterOutlet,
SidebarComponent,
HeaderComponent,
MyFilesComponent,
TrashComponent,
ModalComponent,
],
templateUrl: './app.component.html',
styleUrl: './app.component.css',
})
export class AppComponent implements AfterViewInit {
constructor(
private applicationRef: ApplicationRef,
private injector: Injector,
private componentFactoryResolver: ComponentFactoryResolver
) {}
private portalOutlet: DomPortalOutlet;
private modalPortal: ComponentPortal<ModalComponent>;
ngAfterViewInit() {
this.portalOutlet = new DomPortalOutlet(
document.body,
this.componentFactoryResolver,
this.applicationRef,
this.injector
);
this.modalPortal = new ComponentPortal(ModalComponent);
this.portalOutlet.attach(this.modalPortal);
}
}
This is working. But what to use instead of the ComponentFactoryResolver? When I don't pass the factory resolver to the DomPortalOutlet the modal doesn't show up at all.
Any help is appreciated.
UPDATE:
I tried this:
export class AppComponent implements AfterViewInit {
constructor() {}
public vcr = inject(ViewContainerRef);
ngAfterViewInit() {
const compRef = this.vcr.createComponent(ModalComponent);
compRef.changeDetectorRef.detectChanges();
}
}
It seems to work. It's simpler. But I don't understand why the modal is rendered as a child of the body. It's what I want but I didn't specify that.
Does that mean that portal from the angular cdk is not needed to dynamically inject a component anywhere in the DOM?