I want to call scrollIntoView on a HTML element in a component.
In angular.js 1 I can do something like this in the controller:
var element = $window.document.getElementById(id);
element.scrollIntoView({ behavior: "smooth", block: "start" });
How can I do the same thing in angular 2+ ?
First add a template reference variable in the element (the #myElem
):
<p #myElem>Scroll to here!</p>
Then create a property in the component with attribute ViewChild
, and call .nativeElement.scrollIntoView
on it:
export class MyComponent {
@ViewChild("myElem") MyProp: ElementRef;
ngOnInit() {
this.MyProp.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });
}
}
You could intercept the NavigationEnd event
private scrollToSectionHook() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
const tree = this.router.parseUrl(this.router.url);
if (tree.fragment) {
const element = document.querySelector('#' + tree.fragment);
if (element) {
setTimeout(() => {
element.scrollIntoView({behavior: 'smooth', block: 'start', inline: 'nearest'});
}, 500 );
}
}
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With