事件发射器从bootstrap模态到父级

Nep*_*eph 6 ng-bootstrap angular

我想将模态事件从模态组件传递给模态的父组件,但由于某种原因,我似乎无法让EventEmitter工作.如果有人有想法,将不胜感激.主要代码如下,从ng-bootstrap演示分叉的(非工作)插件在这里:http://plnkr.co/edit/xZhsqBV2mQaPxqFkoE7C?p = preview

app.ts

@Component({
  selector: 'my-app',
  template: `
    <div class="container-fluid" (notifyParent)="getNotification($event)">
    <template ngbModalContainer></template>
    <ngbd-modal-component ></ngbd-modal-component>
  </div>
  `
})
export class App {
      getNotification(evt) {
        console.log('Message received...');
    }
}
Run Code Online (Sandbox Code Playgroud)

莫代尔,component.ts

import {Component, Input, Output, EventEmitter} from '@angular/core';

import {NgbModal, NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'ngbd-modal-content',
  template: `
    <div class="modal-body">
      <p>Hello, {{name}}!</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-secondary" (click)="activeModal.close('Close click')">Close</button>
      <button type="button" class="btn btn-secondary" (click)="notify()">Notify</button>
    </div>
  `
})
export class NgbdModalContent {
  @Input() name;
  @Output() notifyParent: EventEmitter<any> = new EventEmitter();
  constructor(public activeModal: NgbActiveModal) {}

      notify(){
        console.log('Notify clicked...');
        this.notifyParent.emit('Here is an Emit from the Child...');
    }
}

@Component({
  selector: 'ngbd-modal-component',
  templateUrl: 'src/modal-component.html'
})
export class NgbdModalComponent {
  constructor(private modalService: NgbModal) {}

  open() {
    const modalRef = this.modalService.open(NgbdModalContent);
    modalRef.componentInstance.name = 'World';
  }
}
Run Code Online (Sandbox Code Playgroud)

Hir*_*iya 13

更新的答案:

最后,我找到了解决问题的方法.我不确定您是否仔细研究了ng-bootstrap网站上为模态组件提供的所有示例.

您需要使用内容组件中的activeModal.close()方法返回结果.该值将在Modal Component中获取,然后您可以执行任何操作.我创造了一个工作的Plunker,它基本上是官方插件的叉子,它的功能就像魅力一样.

老答案:

我认为您已将事件处理代码放在错误的位置,这就是您没有获得事件通知的原因.

以下是app.ts上的工作模板

  template: `
  <div class="container-fluid">
    <template ngbModalContainer></template>
    <ngbd-modal-component (notifyParent)="getNotification($event)"></ngbd-modal-component>
  </div>
  `
Run Code Online (Sandbox Code Playgroud)

还修改了modal-component.ts中的Notify函数代码

  notify(){
    console.log('Notify clicked...');
    this.notifyParent.emit('Here is an Emit from the Child...');
    this.activeModal.close('Notify click');
}
Run Code Online (Sandbox Code Playgroud)

我已经分叉并修改了你的插件,使它在这里工作


Ves*_*shi 8

在 angular 7 中接受的答案不起作用。所以我找到了新的解决方案。它与那里相似,但略有变化。

不应在子组件的打字稿文件中更改任何内容。您需要为@output和emit函数执行常规代码。但是您需要对父类型脚本文件进行一些更改。下面的代码正在为我收集事件和数据。

open() {
  const modalRef = this.modalService.open(NgbdModalContent);
  // componentInstace didnot work here for me
  // modalRef.componentInstance.name = 'World';
  modalRef.content.notifyParent.subscribe((result)=>{
       console.log(result);   
  })
}     
Run Code Online (Sandbox Code Playgroud)