I have generated one back button component in my Angular 15 project and I want to show this back button across multiple pages in my project. I want to dynamically go back to previous screen using Angular routing so I have defined the back button component like:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-back-button',
templateUrl: './back-button.component.html',
styleUrls: ['./back-button.component.css']
})
export class BackButtonComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit(): void {
}
goBack(url: string): void {
this.router.navigate([url]);
}
}
<button mat-raised-button color="primary" class="centered-button">
<mat-icon>reply</mat-icon>
<span class="button-text">Back</span>
</button>
</div>
<app-back-button (click)="goBack('/')"></app-back-button>
</div>
This won’t work because goBack method should be in component where it is used but I don’t want to define goBack() method in every component where back button is used. I want back button component to dynamically handle the routing.
2
Answers
You can use the Location Service from @angular/common.
If it is just simply to go back, you could use the location service and call it from the button component self: