First you have to listen to browser back navigation event. There are multiple ways to do that (check this thread for details). Here I choosed to use Angular Location service.
Then, when this event is triggered, you have to programmatically close the modal. This can be done using Bootstrap Modal API, calling $('#myModal').modal('hide')
.
Based on your code snippet, I assume that you are using bootstrap by including it traditionnaly (not using existing Angular integration like ng-bootstrap).
Here is a simple Stackblitz example demonstrating a working solution.
First click on the button to open the modal, then click on browser back button and see that modal is automatically closed.
Component
import { Component, ElementRef, ViewChild } from '@angular/core';
import { Location } from "@angular/common";
declare const $:any;
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('modal') modal: ElementRef;
constructor(private location: Location) {
// simulate a navigation history adding consecutive hashs
window.location.hash = 'hash1';
window.location.hash = 'hash2';
window.location.hash = 'hash3';
// when location change...
this.location.subscribe(location => {
// ...close popup
$(this.modal.nativeElement).modal('hide');
});
}
}
Template
<!-- Modal trigger button -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Click me to open modal
</button>
<!-- Modal -->
<div #modal class="modal fade" id="exampleModal" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
Now click on browser previous or next button to see modal closing.
</div>
</div>
</div>
</div>