To maintain a record of your browsing history, consider using a service to store it. You can add URLs to the history when navigation ends and remove them when the back button is pressed.
Here is an example of a NavigationService class:
export class NavigationService {
public history: string[] = [];
constructor(private router: Router) {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
if (this.history[this.history.length - 1] != event.urlAfterRedirects)
this.history.push(event.urlAfterRedirects);
}
});
}
back(): void {
if (this.history.length > 1) {
const route = this.history.pop();
this.router.navigate([this.history[this.history.length - 1]]);
}
}
}
You can add a button to your component and inject the NavigationService into its constructor:
constructor(public navigationService:NavigationService) {}
<button [disabled]="navigationService.history.length<=1"
(click)="navigationService.back()">back</button>