通过Modal Service将数据传递给Component

问题描述 投票:-1回答:1

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

如何通过Modal服务与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();
  }

}
angular angular6 angular7
1个回答
-1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.