As I develop a service in Angular to display components inside a modal, I have encountered an issue. After injecting the component content into the modal and adding it to the page's HTML, the functionality within the component seems to be affected.
For example, when navigating to the component directly through its route, everything works as expected. I can input data into forms, validate it, and interact with buttons. However, when the same component is opened via the modal service, it remains unresponsive. Even after filling out all the fields, the component stays invalid and unchanging, almost as if nothing has been entered at all.
Below is a snippet of my code:
import { Injectable, Injector, ComponentFactoryResolver, Type, Inject } from "@angular/core";
import { Observable, Subject } from "rxjs";
import { ModalComponent } from "../components/modal/modal.component";
import { DOCUMENT } from "@angular/common";
@Injectable({
providedIn: 'root'
})
export class ModalService {
private modalNotifier!: Subject<void>;
constructor(private resolver: ComponentFactoryResolver, private injector: Injector, @Inject(DOCUMENT) private document: Document) {}
open(component: Type<any>, options: { title?: string, width?: string, height?: string }): Observable<any> {
// Create the modal component.
const modalComponentFactory = this.resolver.resolveComponentFactory(ModalComponent);
const modalDynamicComponent = modalComponentFactory.create(this.injector);
// Configure internal variables for the modal.
modalDynamicComponent.instance.closeEvent.subscribe(() => this.close());
modalDynamicComponent.instance.title = options?.title;
modalDynamicComponent.instance.width = options?.width;
modalDynamicComponent.instance.height = options?.height;
// Detect changes in instance variables.
modalDynamicComponent.changeDetectorRef.detectChanges();
// Create the specific component.
const componentFactory = this.resolver.resolveComponentFactory(component);
const componentRef = componentFactory.create(this.injector);
componentRef.changeDetectorRef.detectChanges();
// Add the created component content to the modal.
modalDynamicComponent.instance.contentViewRef.insert(componentRef.hostView);
// Append the modal to the page.
this.document.body.appendChild(modalDynamicComponent.location.nativeElement);
this.modalNotifier = new Subject();
return this.modalNotifier.asObservable();
}
close() {
this.modalNotifier.next();
this.modalNotifier.complete();
}
}