As many of the answers don't take into account all the aspects of back navigation,
I've created a little library that does the trick.
It handles
- Browser history
- Fallback when clicking on the back button when not routed yet
- Customized fallback
Installation
npm install ngx-back-button
Standalone (>= v19.1)
import { NgxBackButtonServiceProvider } from 'ngx-back-button'
bootstrapApplication(AppComponent, {
providers: [
{ // This is optional
provide: NgxBackButtonServiceProvider,
useValue: {
rootUrl: '/custom', // Or any custom root URL
fallbackPrefix: '/tabs', // For library users
},
},
],
}).catch((err) => console.error(err));
Module (<= v.19.0)
import { NgxBackButtonModule, NgxBackButtonService } from 'ngx-back-button'
imports: [
NgxBackButtonModule.forRoot(), // Default rootUrl === '/'
// Or
NgxBackButtonModule.forRoot({
rootUrl: '/custom', // Or any custom root url
fallbackPrefix: '/tabs' // For libraries users
}),
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: () => () => null,
deps: [NgxBackButtonService],
multi: true,
},
]
Then where you need to navigate back
// foo.component.ts
import { NgxBackButtonService } from 'ngx-back-button'
// ...
constructor(public ngxBackButtonService: NgxBackButtonService) {}
navigateBack() {
this.ngxBackButtonService.back()
}
Also work with a directive
<button ngxBackButton>
Back
</button>