Reputation: 2272
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?
Upvotes: 1
Views: 529
Reputation: 96969
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
Upvotes: 2