如何从另一个组件打开 ng bootstrap 模态?

how to open ng bootstrap modals from another component?

我想在组件 1 的帮助下从另一个模块打开或关闭模态。但是目前我无法访问该组件中模态的 ngBootstrap 的 modalRef,因此我可以 close/open 它。

假设这个场景

一个模块

<component1></component1>

另一个模块 这个模块有多个组件,每个组件都有模态,我需要根据组件 1 的条件显示或隐藏。

<component2> //have ng bootstrap modal in it </component2>
<component3> //have ng bootstrap modal in it </component3>
<component4> //have ng bootstrap modal in it </component4>
<component5> //have ng bootstrap modal in it </component5>
<component6> //have ng bootstrap modal in it </component6>

目前我只是在该模块中放置一个隐藏按钮,然后使用来自另一个组件的 JavaScript 单击它,我知道这不是一个好方法,所以我希望有人给我一些调用这些模式的方法或告诉我设计中是否有任何更改。

据我所知,我认为服务会很好。但在改变设计之前,我想听听别人的意见。谢谢

看到这个答案,你可以创建一个没有任何外部库的自定义模式:

问题是 NgbModule 可用于模块而不是应用程序中的其他模块。当导入模块时(此处 NgbModule),它仅特定于该模块。所以要么你必须在另一个模块中包含 NgbModule 或在当前模块中导出它并在另一个模块中导入当前模块。

在其他模块中导入它

@NgModule({
  imports: [
    NgbModule,
  ],

或者导入第二个已经包含 NgbModule 模块的第一个模块。

使用 Observable 创建一个服务并触发并发出用户点击关闭按钮。

单击关闭按钮后,可以在任何其他组件中捕获事件并执行操作。

服务

@Injectable()
export class SomeService {
   public popup: Subject<any> = new Subject<any>();

  constructor() {}
}

Component 有模态要关闭。

constructor(SomeService: SomeService){
  this.SomeService.popup.subscribe((val)=>{
     if(val === 'close') {
       // close the modal
     }
   });
}

现在,您可以从其他组件触发事件以关闭模型。您可以从任何组件执行关闭。

constructor(private SomeService: SomeService) {}

SomeMethod() {
  this.someService.popup.next('close');
}

我刚遇到同样的问题并找到了这个帖子,Aniruddha Das 在强调基本要求方面做得很好,但我发现它错过了下一点的 TemplateRef 用法,以防万一其他人有这个问题我会完成它。使用与 Aniruddha 相同的模型

模板:

<ng-template #updatemodal>
  <div class="modal">
    stuff here...
  </div>
</ng-template>

分量:

@ViewChild('updatemodal')
private modalRef: TemplateRef<any>;

private myModal<any>;

constructor(SomeService: SomeService, modalService: NgbModal){
  this.SomeService.popup.subscribe((val)=>{
     if(val === 'open') {
       this.myModal = this.modalService.open(this.modalRef);
     }
   });
}

引用已创建的模态是在响应中允许更多使用和灵活性的好方法,并使用:

this.myModal.result.then((result) =>{
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });

来自 NgBootstrap 网站

  1. app.module.ts:

    {
        ...
        imports [...],
        entryComponents: [ModalComponent],
        ...
    }
    
  2. 写下你的模型,作为 here 的 "Components as content" 部分。

  3. 在您使用模式的组件中:

    • 导入 ModalComponent 和依赖项
    • 构造函数(私有模态服务:NgbModal)
    • 最好将其放入方法中:

      const modal = this.modalService.open(ModalComponent);
      modal.componentInstance.title = "Dialog";
      modal.componentInstance.body = "Your message";