I want to navigate from one page to another and jump directly to one control in the middle of the destination page. Normally, we can use a hashtag "#" follow with the name or ID of the control.
However, this method does work that well in Angular 2. I have tried method like Angular2 Routing with Hashtag to page anchor. With that method, the url does end with "#myId" but the page doesn't actually jump.
Do we have other ways to achive this?
Angular documentation project has AutoScrollService service. You can try to use it. auto-scroll.service.ts
/**
* A service that supports automatically scrolling elements into view
*/
@Injectable()
export class AutoScrollService {
constructor(
@Inject(DOCUMENT) private document: any,
private location: PlatformLocation) { }
/**
* Scroll to the element with id extracted from the current location hash fragment
* Scroll to top if no hash
* Don't scroll if hash not found
*/
scroll() {
const hash = this.getCurrentHash();
const element: HTMLElement = hash
? this.document.getElementById(hash)
: this.document.getElementById('top-of-page') || this.document.body;
if (element) {
element.scrollIntoView();
if (window && window.scrollBy) { window.scrollBy(0, -80); }
}
}
/**
* We can get the hash fragment from the `PlatformLocation` but
* it needs the `#` char removing from the front.
*/
private getCurrentHash() {
return this.location.hash.replace(/^#/, '');
}
}