我在Angular 7 StackBlitz Example有一个模态服务用作:
export class AppComponent {
constructor(private modalService: ModalService) { }
openModal() {
this.modalService.open({
component: HelloComponent
});
}
}
export class HelloComponent extends Modal {
@Input property: string;
}
如何通过Modal服务与HelloComponent共享数据?
this.modalService.open(HelloComponent, { property: 'hello' });
不知道如何更改我的服务来实现这一目标。我猜想:
this.componentRef = this.componentFactoryResolver.resolveComponentFactory(component.component).create(this.injector);
this.componentRef.instance.modal = this;
this.appRef.attachView(this.componentRef.hostView);
return (this.componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
ModalService
import { ApplicationRef, ComponentFactoryResolver, EmbeddedViewRef, Injectable, Injector } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ModalService {
private componentRef: any;
private modalContainer: any;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector) { }
private createFormModal(component: any): Element {
this.componentRef = this.componentFactoryResolver.resolveComponentFactory(component.component).create(this.injector);
this.componentRef.instance.modal = this;
this.appRef.attachView(this.componentRef.hostView);
return (this.componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
}
open(component: any): void {
const alertElement = this.createFormModal(component);
const content = document.createElement('div');
content.classList.add('modal');
content.appendChild(alertElement);
this.modalContainer = document.createElement('div');
this.modalContainer.classList.add('modal');
this.modalContainer.appendChild(content);
document.body.appendChild(this.modalContainer);
}
close(): void {
this.appRef.detachView(this.componentRef.hostView);
this.modalContainer.parentNode.removeChild(this.modalContainer);
this.componentRef.destroy();
}
}
看起来你正在尝试创建自己的模态类/服务。作为参考,我建议您在项目中使用ng-bootstrap模式对话框,然后探索如何设计NgbActiveModal类。