I am using angular 11 for web SPA and I am facing an issue with navigation back to previous page. How can I keep the position of previous page which scroll to or that action is default browser's behavior?
Thank you very much for your consideration!
CodePudding user response:
I don't know exactly if you want to get back to previous page programatically.
If that is what you want, you can do that with "location":
import { Location } from '@angular/common';
....
constructor(
...
private _location: Location,
...
) {
...
}
backToPreviousPage() {
this._location.back();
}
CodePudding user response:
i would suggest using a service to manage your state and position. depending on how much navigation history you want to keep would make this more or less complicated.
a simple service would look something like this.
import { Location } from '@angular/common';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root',
})
export class NavService {
private _lastScrollPositionY: number;
private _lastScrollPositionX: number;
constructor(
private _location: Location,
private _router: Router,
) { }
back() {
this._location.back();
if (this._lastScrollPositionY || this._lastScrollPositionX) {
window.scroll(this._lastScrollPositionX, this._lastScrollPositionY);
this._lastScrollPositionY = this._lastScrollPositionX = null;
}
}
navigate(route: string[]) {
this._lastScrollPositionX = window.scrollX;
this._lastScrollPositionY = window.scrollY;
this._router.navigate(route)
}
}
``