I want to be able to scroll to a target when a button is pressed. I was thinking something like this.
<button (click)="scroll(#target)">Button</button>
And in my component.ts a method like.
scroll(element) {
window.scrollTo(element.yPosition)
}
I know that the code above is not valid but just to show what I was thinking. I've just started to learn Angular 4 with no previous experience of Angular. I've been searching around for something like this but all the examples are in AngularJs which differs alot to Angular 4
in angular you can use ViewChild and ElementRef: give your html element a ref
and inside your component:
you can use this.myDivRef.nativeElement to get to your element
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)
on the .ts file,
You can achieve that by using the reference to an angular DOM element as follows:
Here is the example in stackblitz
the component template:
You could do it like this:
and then in your component:
Edit: I see comments stating that this no longer works due to the element being undefined. I created a StackBlitz example in Angular 7 and it still works. Can someone please provide an example where it does not work?
In angular 7 works perfect
HTML
In component
You can do this by using jquery :
ts code :
html code :
Apply this on elements you want to scroll :
Here is a stackblitz sample.