How can I rewrite the code so it’s nt using deprecated ComponentFactoryResolver and still does the same stuff (open a modal in the body)?
import { ComponentFactoryResolver, Inject, Injectable, Injector, TemplateRef } from "@angular/core";
import { ModalComponent } from "../../shared/components/modal/modal.component";
import { DOCUMENT } from "@angular/common";
import { Observable, Subject } from "rxjs";
@Injectable()
export class ModalService {
private modalNotifier?: Subject<string>;
constructor(
private resolver: ComponentFactoryResolver,
private injector: Injector,
@Inject(DOCUMENT) private document: Document
) {}
open(content: TemplateRef<any>, options?: { size?: string; title?: string }): Observable<string> {
const modalComponentFactory = this.resolver.resolveComponentFactory(
ModalComponent
);
const contentViewRef = content.createEmbeddedView(null);
const modalComponent = modalComponentFactory.create(this.injector, [
contentViewRef.rootNodes,
]);
modalComponent.instance.size = options?.size;
modalComponent.instance.title = options?.title;
modalComponent.instance.closeEvent.subscribe(() => this.closeModal());
modalComponent.instance.submitEvent.subscribe(() => this.submitModal());
modalComponent.hostView.detectChanges();
this.document.body.appendChild(modalComponent.location.nativeElement);
this.modalNotifier = new Subject();
return this.modalNotifier?.asObservable();
}
closeModal() {
this.modalNotifier?.complete();
}
submitModal() {
this.modalNotifier?.next('confirm');
this.closeModal();
}
}
I tryed using instead of the factory
const component = this.viewContainerRef.createComponent(ModalComponent, options, this.injector, contentViewRef.rootNodes);
And I get Argument of type ‘typeof ModalComponent’ is not assignable to parameter of type ‘ComponentFactory’.
The think is u have to use ComponentFactory which is also deprecated
Stanislav Semashko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.