skip to Main Content

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


  1. You can use the Location Service from @angular/common.

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    import { Location } from '@angular/common';
    
    @Component({
      selector: 'app-back-button',
      templateUrl: './back-button.component.html',
      styleUrls: ['./back-button.component.css']
    })
    
    export class BackButtonComponent implements OnInit {
        
    constructor(private router: Router, private location: Location) {}
          
    ngOnInit(): void {}
        
     goBack(): void {
       this.location.back();
     }
    }
    
    Login or Signup to reply.
  2. If it is just simply to go back, you could use the location service and call it from the button component self:

    import { Location } from '@angular/common';
    import { Component, inject } 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 {
      readonly location = inject(Location);
    }
    
     <button mat-raised-button color="primary" class="centered-button"
             (click)="location.back()">
       <mat-icon>reply</mat-icon>
       <span class="button-text">Back</span>
     </button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search