How to navigate parent component from a model popup in angular?

Viewed 243

Suppose that I have two components. component(A) and a component(B).

I want to open the (B) component as a NgbModal by using component (A).

The below code is in component (A) to open component (B) as a model popup.

constructor(private modalService: NgbModal)
{
}

openB()
  {

this.modalService.open(BComponent);

}

Now suppose that there is a button in the model component (B) and the function is like this.

searchData()
{
//process to find data.
//

 this.activeModal.close();
 this.router.navigate(['/A']);
}

Issue :- (A) component is not navigating and not calling ngOnInit() in component (A). How can I navigate the (A) component after clicking button in model popup (B)?

Thanks in advance.

2 Answers

I am not really sure you need to redirect onClose. As per the example given by NgbModal in Stackbliz. They have clearly provided a callback on close. Using callback you can call the content of ngOnInit.

For example

 In your component A 

 ngOnInit(){
  this.yourNgOnInit();  
  }

  yourNgOnInit(){
   // do your stuff here.
  }

  open(content) {
    this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
       // call your content here on close after save
      this.yourNgOnInit()
    }, (reason) => {
      // call your content here on close wihout save     
      this.yourNgOnInit()
    });

Your Component A is already rendered and it's because that after closing Modal it will not be rendered again. ngOnInit() will call whenever e Component will be rendered. So you don't need to Navigate to component again. Just subscribe for the close event and on the result do your function call searchResult() like this:

check here for an example: stackblitz

closeModal() { 
  this.activeModal.close(); 
  this.searchResult(); 
}

searchResult() {
 ...
}
Related