Передача данных в Компонент через Модальный Сервис - PullRequest
0 голосов
/ 15 апреля 2019

У меня есть модальная служба в Angular 7 Пример StackBlitz используется как:

export class AppComponent  {

  constructor(private modalService: ModalService) { }

  openModal() {
    this.modalService.open({
      component: HelloComponent
    });
  }

}

export class HelloComponent extends Modal {
  @Input property: string;
}

Как поделиться данными с 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();
  }

}

1 Ответ

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

похоже, что вы пытаетесь создать свой собственный модальный класс / сервис. Для справки я бы предложил использовать в вашем проекте модальное диалоговое окно ng-bootstrap, а затем изучить, как разработан класс NgbActiveModal.

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