首页 > 解决方案 > 通过 Modal Service 向 Component 传递数据

问题描述

我在 Angular 7 StackBlitz 示例中有一个模态服务,用作:

export class AppComponent  {

  constructor(private modalService: ModalService) { }

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

}

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

如何通过 Modal Service 与 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;

模态服务

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

}

标签: angularangular6angular7

解决方案


看起来您正在尝试创建自己的模态类/服务。作为参考,我建议您在项目中使用 ng-bootstrap 模态对话框,然后探索 NgbActiveModal 类的设计方式。


推荐阅读