Выдать событие в родительский компонент из модального в ng-bootstrap - PullRequest
0 голосов
/ 18 сентября 2018

Я прочитал кучу о том, как это сделать, но, похоже, ничего не работает.У меня есть модальный компонент, который вызывается из родительского компонента с помощью 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 голосов
/ 19 сентября 2018

Я бы предложил другой подход вместо подписки, создав экземпляр класса компонента

Создайте новый сервис для повторного использования 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);
    })
  }

}
...