Открывать только один модальный при нажатии кнопки - PullRequest
0 голосов
/ 15 апреля 2019

Я создал модальную службу в Angular 7 Пример StackBlitz :

Модальный

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();
  }

}

Я могу открыть модал при нажатии на кнопку ...

Проблема в том, что я могу открыть более одного.

Как я могупри нажатии кнопки открывается только один модал?

Ответы [ 2 ]

1 голос
/ 15 апреля 2019

Поскольку служба является одноэлементной (один экземпляр за всю жизнь приложения), вы можете просто сохранить состояние модального режима в службе следующим образом:

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;
  }

}
0 голосов
/ 15 апреля 2019

Поскольку этот сервис является одноэлементным, вы можете просто установить флаг при открытии модального окна и отключить его при закрытии. Затем в своей функции open вы можете проверить, установлен ли флаг на true или нет, и если это так, не открывайте второй модал.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...