3

我正在尝试制作一个可以从同一个模态本身调用的可重用模态组件。

我如何配置组件和模式,以便当可重用组件打开时,旧实例将直接关闭?

下面是我的堆栈闪电战。

https://stackblitz.com/edit/angular-nested-component-modal-ngx-bootstrap-n

4

1 回答 1

3

我会使用一种模态...

这是策略

  1. 在应用程序组件上有模态
  2. 创建一个服务,当用户想要打开一个新的模式时进行通信
  3. 从每个组件按钮调用服务

让我们从定义我们的服务开始

我的.service.ts

import { Injectable } from "@angular/core";
import { BehaviorSubject, Subject } from "rxjs";

interface IModalParams {
  component: any;
  config?: any;
  title?: any;
}
@Injectable()
export class MyService {
  modalOpen$ = new BehaviorSubject(false);
  component;
  config;
  title;
  show({ component, config, title }: IModalParams) {
    this.component = component;
    this.config = config;
    this.title = title;
    this.modalOpen$.next(true);
  }
}

所以我们定义了一个 show 方法来设置一些变量(component,configurationtitle

我们还定义了一个主题modalOpen$。现在,当用户打开新模式时,将通知订阅此属性的任何属性

app.component.ts

  ngOnInit() {
    this.myService.modalOpen$.pipe(
      tap(() => this.modalRef?.hide()),
      filter(isOpen => isOpen)
    ).subscribe({
      next: () => {
        const {component, config, title} = this.myService
          this.modalRef = this.modalService.show(component, config);
          if(title) {
            this.modalRef.content.title = title; 
          }
      }
    })
  }

这里我们订阅modalOpen$并打开或关闭提供的组件

任何其他.component.ts

 this.myService.show({
     component: ModalContentComponent,
     config: {
      ignoreBackdropClick: false
    },
    title: "Modal with component"
   })
  }

在其他组件中,我们现在可以使用show上面指定的方法

在此处查看演示

于 2021-03-27T01:54:29.470 回答