Search code examples
ionic2

Ionic2: how to catch events from within a Modal component (created from ModalController)?


Is there a way to catch local events emitted from within a Modal component (created with ModalController) without dismissing, and not have to use the global Events or a service?

The Angular way to do this is to use listen from Renderer, but I don't see how to get the proper reference to the component instance in this case.

MyComponent.ts

...
export class MyComponent {
  @Output() myAwesomeEvent = new EventEmitter<string>();

  fireEvent() {
    this.myAwesomeEvent.emit('payload');
  }
}

Parent.ts

...
const modal = this.modalCtrl.create(MyComponent);
// how do I catch 'myAwesomeEvent' emitted from within MyComponent?
...

Solution

  • Access the instance property in modal.

    const modal = this.modalCtrl.create(MyComponent);
    modal.didEnter.subscribe(() => {
        modal.instance.myAwesomeEvent.subscribe(....)
    });
    

    Ionic Version 3:

    this.modalCtrl.create(MyComponent).present().then((result) =>{
        result.instance.myAwesomeEvent.subscribe(....)
    });