我在Angular 7 StackBlitz Example中创建了模态服务:
模式
export class Modal {
protected modal: any = null;
close() {
this.modal.close();
}
}
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();
}
}
点击按钮...我可以打开模态...
问题是我可以打开多个。
如何确保单击按钮时仅打开一个模式?
答案 0 :(得分:1)
由于服务是单例(在整个应用程序生命中都是一个实例),因此您可以像这样在服务中保留模态的状态:
import { ApplicationRef, ComponentFactoryResolver, EmbeddedViewRef, Injectable, Injector } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ModalService {
private componentRef: any;
private modalContainer: any;
private alertElement: 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 {
if(this.alertElement) return;
this.alertElement = this.createFormModal(component);
const content = document.createElement('div');
content.classList.add('modal');
content.appendChild(this.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();
this.alertElement = null;
}
}
答案 1 :(得分:0)
由于此服务是单例服务,因此您可以仅在打开模式时设置标志,而在关闭模式时将其关闭。然后在打开的函数中,您可以检查标志是否为true,如果不正确,则不要打开第二个模式。