5

I am opening a modal using component as a template, everything is ok, modal opens and I am subscribing to onHide Event, subscription works also.

but I have a challenge here, I want to send a specific reason for example: 'message added successfully' as the reason . how can I do that? how can I send a specific string as a reason?

currently, I am trying to set a value in MessageAddComponent component and access it in parent component using bsModalRef.Content, but it is not a good idea.

newMessage() {
    this.bsModalRef = this.modalService.show(MessageAddComponent, {
        class: 'modal-lg'
    });
    this.subscriptions.push(this.modalService.onHide.subscribe((reason: string) => {
        // i dont like this approach
        if (this.bsModalRef.content.anySuccessfulAction) {
            console.log('foo and bar')
        }
        this.unsubscribe();
    }));
}
Arash
  • 3,458
  • 7
  • 32
  • 50

4 Answers4

8

To simplify your subscription you can create "onetime" subscription via .take() or first() operator:

this.modalService.onHide
    .pipe(take(1))
    .subscribe(() => {
        console.log(this.bsModalRef.content)
    });
Ihor
  • 571
  • 6
  • 10
6

found solution finally:

inject BsModalService in the component that is used as modal and then set dismiss reason as bellow

this.modalService.setDismissReason(theReason);
Arash
  • 3,458
  • 7
  • 32
  • 50
2

Good solution put together:

this.modalService.onHide.pipe(take(1), filter(reason => reason === 'yourReason')).subscribe(() => {
    // Do anything here, this will get called only once
});

And then in your modal before hiding your modal:

this.modalService.setDismissReason('yourReason');
Bartando
  • 719
  • 8
  • 26
0

When we call modalRef.show(component), it goes to the component but it will not show anything on the screen.
If you observe it using debugger, then after several lines of execution then it will show the popup.
Assume that i have

ngOnInit(){
    method1();
    method2();
}
method1(){
    modalRef.show(component);
    modalRef.hide();
}
method2(){
    modalRef.show(component);
    modalRef.hide();
}

When i do this, the modal2 will popup first and close. The modal1 is popped up, but it will not hide because the execution of hide is already over and it will not go there again in method 1.

Marcus
  • 822
  • 1
  • 8
  • 27