I want to be able to scroll to a target when a button is pressed. I was thinking something like this.
In Angular you can use ViewChild
and ElementRef
:
give your HTML element a ref
<div #myDiv >
and inside your component:
import { ViewChild, ElementRef } from '@angular/core';
@ViewChild('myDiv') myDivRef: ElementRef;
you can use this.myDivRef.nativeElement
to get to your element
You can do this by using jquery :
ts code :
scrollTOElement = (element, offsetParam?, speedParam?) => {
const toElement = $(element);
const focusElement = $(element);
const offset = offsetParam * 1 || 200;
const speed = speedParam * 1 || 500;
$('html, body').animate({
scrollTop: toElement.offset().top + offset
}, speed);
if (focusElement) {
$(focusElement).focus();
}
}
html code :
<button (click)="scrollTOElement('#elementTo',500,3000)">Scroll</button>
Apply this on elements you want to scroll :
<div id="elementTo">some content</div>
Here is a stackblitz sample.
You can scroll to any element ref on your view by using the code block below. Note that the target (elementref id) could be on any valid html tag.
On the view(html file)
<div id="target"> </div>
<button (click)="scroll()">Button</button>
on the .ts
file,
scroll() {
document.querySelector('#target').scrollIntoView({ behavior: 'smooth', block: 'center' });
}
I have done something like what you're asking just by using jQuery to find the element (such as document.getElementById(...)
) and using the .focus()
call.
You can achieve that by using the reference to an angular DOM element as follows:
Here is the example in stackblitz
the component template:
<div class="other-content">
Other content
<button (click)="element.scrollIntoView({ behavior: 'smooth', block: 'center' })">
Click to scroll
</button>
</div>
<div id="content" #element>
Some text to scroll
</div>
I need to do this trick, maybe because I use a custom HTML element. If I do not do this,
target
in onItemAmounterClick
won't have the scrollIntoView
method
.html
<div *ngFor"...">
<my-component #target (click)="clicked(target)"></my-component>
</div>
.ts
onItemAmounterClick(target){
target.__ngContext__[0].scrollIntoView({behavior: 'smooth'});
}