通过模态服务将数据传递到组件

时间:2019-04-15 17:22:17

标签: angular angular6 angular7

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

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 :(得分:-1)

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