我正在尝试创建自己的模态,除了单击外部以将其关闭之外,其他所有功能均正常。我收到错误消息“无法读取未定义的属性'hostView' 在DomService.removeComponent上,这是我的代码: 在我的布局中:
<div id="modal-container" class="hidden" (click)="removeModal()">
<div id="app-modal"></div>
</div>
removeModal() {
this.modalService.destroy();
}
我的modalService:
init(component: any, inputs: object, outputs: object, mc?: string) {
this.component = component;
const componentConfig = {
inputs: inputs,
outputs: outputs
};
this.domService.appendComponentTo(this.modalElementId, component, componentConfig);
document.getElementById(this.modalElementIdWrapper).className = 'show';
document.getElementById(this.overlayElementId).className = 'show';
document.getElementById(this.modalElementId).addEventListener('click', function(event) {
event.stopPropagation();
});
document.getElementById(this.modalElementId).className = 'dialog';
document.getElementById(this.modalElementId).className = mc + ' dialog';
}
destroy() {
this.domService.removeComponent();
document.getElementById(this.modalElementIdWrapper).className = 'hidden';
document.getElementById(this.overlayElementId).className = 'hidden';
}
我的Dom服务:
public appendComponentTo(parentId: string, child: any, childConfig?: childConfig) {
// Create a component reference from the component
const childComponentRef = this.componentFactoryResolver
.resolveComponentFactory(child)
.create(this.injector);
// Attach the config to the child (inputs and outputs)
this.attachConfig(childConfig, childComponentRef);
this.childComponentRef = childComponentRef;
// Attach component to the appRef so that it's inside the ng component tree
this.appRef.attachView(childComponentRef.hostView);
// Get DOM element from component
const childDomElem = (childComponentRef.hostView as EmbeddedViewRef<any>)
.rootNodes[0] as HTMLElement;
// Append DOM element to the body
document.getElementById(parentId).appendChild(childDomElem);
}
public removeComponent() {
this.appRef.detachView(this.childComponentRef.hostView);
this.childComponentRef.destroy();
}