首页 > 解决方案 > 角度滚动到动态创建的元素

问题描述

我有一个 Angular 应用程序,当用户单击按钮时,我会在其中检索数据:

getJobNotes() {
  this.jobNoteService.getJobNotes()
    .subscribe(
      result => {
        this.jobNotes = result.jobNotes;
      }
    );
}

我想滚动查看具有特定工作说明 ID 的元素,例如,这可能是 10 个列表中的第 5 个元素。

我尝试了以下方法:

  this.selectedJobNoteId = result.selectedJobNoteId;
  let el = document.getElementById(this.selectedJobNoteId);
  el.scrollIntoView();

在这种情况下,我的“el”变量是未定义的。

在我的 html 中,我正确设置了 ID:

<li *ngFor="let jobNote of jobNotes" id="{{jobNote.jobNoteId}}">

我已经确认 ID 已设置,如果我在 chrome 控制台中使用正确的 ID 运行 document.getElementById,那么我会取回元素 - 我怀疑问题是元素是动态创建的?

标签: angular

解决方案


您可以将模板变量分配给列表项:

<ul *ngIf="users">
  <li #user *ngFor="let userDetail of users">
    <h1>{{ userDetail.name }}</h1>
    <h2>{{ userDetail.username }}</h2>
    <h3>{{ userDetail.email }}</h3>
  </li>
</ul>

然后在 Component 类中,您可以使用ViewChildren. 像这样的东西:

@ViewChildren("user", { read: ElementRef }) renderedUsers: QueryList<ElementRef>;

最后,您可以使用scrollIntoViewa nativeElementof any item 滚动到它:

getData() {
  this.http
    .get("https://jsonplaceholder.typicode.com/users")
    .subscribe(users => {
      this.users = users;
      this.timeoutId = setTimeout(() => {
        const userToScrollOn = this.renderedUsers.toArray();
        userToScrollOn[this.indexToScrollTo].nativeElement.scrollIntoView({
          behavior: 'smooth'
        });
      }, 1000);
    });
}

我在setTimeout这里使用了一个 coz,一旦您获得数据,列表就不会呈现。renderedUsers所以在初始化之前会有一点延迟。

因此,ngOnDestroy还要确保通过调用清除超时clearTimeout(this.timeoutId);


这是您的参考的工作示例演示


推荐阅读