Search code examples
angulartypescriptngfor

How can I scroll to a specified component selector inside ngFor?


I have multiple components run inside *ngFor on the same page. I want to have several button links on the top of the page which can scroll to the component once clicked.

Here are the codes I am trying to follow.

in html file:

<button (click)="scroll(target)"></button>
<div #target>Your target</div>

and in the ts file:

scroll(el: HTMLElement) {
    el.scrollIntoView();
}

but I don't know how could I reference to each of the component selector

Here are some of my code without implementing the above code yet:

//There will be many buttons to link to each of the component.

<button type="button" (click)="scroll()">Click this button to navigate</button>

<div *ngFor="let appdata of appData">
    <app-details [value]="appdata"></app-details>
</div>

The 'appdata' is a json variable including attributes like appID (which could uniquely identify the component), title, description, etc.

Please advice how can I reference the components and maybe suggest how to implement it. Thank You!!


Solution

  • To scroll to an element we can use the window.scrollTo(xpos, ypos) function provided by javascript.

    you could do like this

    first, declare a variable that refers to the window Object

    win:Window=window;
    

    then define the scroll functionality

      scroll(component){
            this.win.scrollTo(0,component.offsetTop);
       }
    

    where component parameter points to the specific element. and component.offsetTop gives the y position of that element.

    and in the HTML,

       <span *ngFor="let target of  win.document.getElementsByTagName('app-details');let i=index" >
            <button  (click)="scroll(target)"  > Go TO {{i}}</button></span>