1

In Angular I am using a Modal Directive inside a component which emits onHide event (EventEmitter) when modal is closed.

This component is a dialog component, its template defines a dialog, Modal Directive (bsModal below) makes it modal.

<div bsModal #modal="bs-modal" class="modal fade" role="dialog" tabindex="-1" [config]="{backdrop: 'static',keyboard:'false'}">
...
</div>

I need to Output a close event from component when Modal Directive emits its onHide event.

Here's how I am doing it:

export class DialogComponent implements OnInit {
    @ViewChild('modal') modal: ModalDirective;
    @Output() close = new EventEmitter<any>(); // Component's close event emitter
    ...
    ngAfterViewInit() {
        this.modal.onHide.subscribe(() => {
            this.close.emit();
        });
    }
    ...
}

Something tells me that there's a better way to achieve this, that somehow I can define component's close event based on directive's onHide observable, which will save me from subscribing directive's onHide.

What is that better way?

abdul-wahab
  • 2,182
  • 3
  • 21
  • 35
  • not getting you much but EventEmitter is better than observable , because if you use observable than you need to detroy/ unsubscribe it also in ngDestroy event – Pranay Rana Mar 14 '18 at 09:02
  • So, how can I relay EventEmitter from within component's template to outside? – abdul-wahab Mar 14 '18 at 09:54

1 Answers1

2

Well, I don't think there's much better way to do this than you have right now. You can however make it a little shorter.

ngAfterViewInit() {
  this.subscription = this.modal.onHide.subscribe(this.close);
}

Just be aware that I'm assuming that onHide never completes nor errors.

Another thing to be aware of is that you need to unsubscribe when the component is destroyed.

onDestroy(): void {
  this.subscription.unsubscribe();
}

Similar question: Pipe RxJS observable to existing subject

martin
  • 93,354
  • 25
  • 191
  • 226