从ng-bootstrap中的模式向父组件发送事件

时间:2018-09-18 20:44:26

标签: angular ng-bootstrap

我已经阅读了很多有关如何执行此操作的信息,但是似乎没有任何效果。我有一个使用ng-bootstrap从父组件调用的模式组件。父级成功将参数传递给模态。但是,我然后想在关闭模态时提醒父母,并告诉父母模态表单中显示的数据是否被修改。

以下是相关代码片段。为了简单起见,我省略了模板,因为它们所做的只是在组件代码中调用相关方法。我是否缺少简单的东西?预先感谢。

模式组件:

export class myModalComponent implements OnInit {

  @Input() myRecordId: number;
  @Output() closeEvent = new EventEmitter<boolean>();

  isDirty: boolean = false;

  // this is called from a button click in the template
  close() {
    this.closeEvent.emit(this.isDirty);
    this.activeModal.close();
  }

}

父组件:

export class myParentComponent implements OnInit {

  // this is called from a button click in the template
  openModal(myRecordId: number) {
    const modalref = this.modal.open(myModalComponent);
    modalref.componentInstance.myRecordId = myRecordId;
    modalref.componentInstance.closeEvent.subscribe(($e) => {
      // when modal is closed I would expect the event to be logged
      // here but I see nothing in the console. :(
      console.log($e);
    })
  }

}

1 个答案:

答案 0 :(得分:2)

我建议通过创建组件类的实例来替代订阅的另一种方法

创建新服务以在多个组件之间重用closeEvent

import {EventEmitter} from 'angular2/core';
export class ModalPopupService {
  closeEvent: EventEmitter<any> = new EventEmitter();
  constructor() {}
  emit(data) {
    this.closeEvent.emit(data);
  }
  getCloseEvent() {
    return this.closeEvent;
  }
}

在您的组件中插入modalPopupService并发出数据

export class myModalComponent implements OnInit {

  @Input() myRecordId: number;
  constructor(private modalPopupService :ModalPopupService ){}
  isDirty: boolean = false;

  // this is called from a button click in the template
  close() {
    this.modalPopupService.emit(this.isDirty);
    this.activeModal.close();
  }

}

现在您可以像这样订阅

export class myParentComponent implements OnInit {
  constructor(private modalPopupService :ModalPopupService ){}


  // this is called from a button click in the template
  openModal(myRecordId: number) {
    const modalref = this.modal.open(myModalComponent);
    modalref.componentInstance.myRecordId = myRecordId;
    this.modalPopupService.getCloseEvent().subscribe(($e) => {
      // when modal is closed I would expect the event to be logged
      // here but I see nothing in the console. :(
      console.log($e);
    })
  }

}