Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go back to previous page in Angular 4 [duplicate]

I want to have back-to-the-previous page.

Previous Page: job.html Current Page: jobDetail.html

As per instructions, I have added import { Location } from '@angular/common'; to the jobDetail.component.ts file at the top followed by

export class MyDetailComponent implements OnInit {
constructor(private location: Location) {}
    ngOnInit() {
        this.location.subscribe(x => console.log(x));
    }
}

I have a html code in jobDetail.html but don't know how to proceed further. How do I add a previous button correctly. There's no easy tutorial for newbies like me.

<a routerLink="">Back</a>
like image 949
Elaine Byene Avatar asked Nov 22 '17 07:11

Elaine Byene


People also ask

How do you navigate to the previous page programmatically?

navigate(LASTPAGE); For example, page C has a Go Back button, Page A -> Page C, click it, back to page A. Page B -> Page C, click it, back to page B.

What is Route snapshot in angular?

If you intend not to update your URL parameter within the same component you are accessing it, then you can use the snapshot. As the name suggests, the parameter would only be accessed once, when the component loads. Hence, it won't be updated, even if you change its value from within the same component.


1 Answers

This worked as posted by Hinrich:

import { Location } from '@angular/common';
// more imports here...

@Component({
  // component's declarations here
})
export class MyComponent {

  constructor(private location: Location) { } // inject Location into class constructor

  cancel() {
    this.location.back(); // <-- go back to previous location on cancel
  }
}

HTML

<a (click)="cancel()">Back</a>
like image 170
Elaine Byene Avatar answered Oct 04 '22 02:10

Elaine Byene