如何在 ngFor 中滚动到指定的组件选择器?

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

我在同一页面的 *ngFor 中有多个组件 运行。我想在页面顶部有几个按钮链接,单击后可以滚动到该组件。

这是我要遵循的代码。

在 html 文件中:

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

并且在 ts 文件中:

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

但我不知道如何引用每个组件选择器

下面是我的一些代码,还没有实现上面的代码:

//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>

'appdata' 是一个 json 变量,包括 appID(可以唯一标识组件)、标题、描述等属性

请告诉我如何引用这些组件,并可能建议如何实现它。谢谢!!

要滚动到一个元素,我们可以使用 window.scrollTo(xpos, ypos) 函数 由 javascript.

提供

你可以这样做

首先,声明一个引用 window 对象的变量

win:Window=window;

然后定义滚动功能

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

其中组件参数指向特定元素。 component.offsetTop 给出该元素的 y 位置。

并在 HTML、

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

你可以这样写。

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

点击滚动按钮,您可以写下您的 TS 以聚焦于此:

const element = document.querySelector(id); // id of the scroll to element
element.scrollIntoView();