How to go back last page
Actually you can take advantage of the built-in Location service, which owns a "Back" API.
Here (in TypeScript):
import {Component} from '@angular/core';import {Location} from '@angular/common';@Component({ // component's declarations here})class SomeComponent { constructor(private _location: Location) {} backClicked() { this._location.back(); }}
Edit: As mentioned by @charith.arumapperuma Location
should be imported from @angular/common
so the import {Location} from '@angular/common';
line is important.
In the final version of Angular 2.x / 4.x - here's the docs https://angular.io/api/common/Location
/* typescript */import { Location } from '@angular/common';// import stuff here@Component({// declare component here})export class MyComponent { // inject location into component constructor constructor(private location: Location) { } cancel() { this.location.back(); // <-- go back to previous location on cancel }}
<button backButton>BACK</button>
You can put this into a directive, that can be attached to any clickable element:
import { Directive, HostListener } from '@angular/core';import { Location } from '@angular/common';@Directive({ selector: '[backButton]'})export class BackButtonDirective { constructor(private location: Location) { } @HostListener('click') onClick() { this.location.back(); }}
Usage:
<button backButton>BACK</button>