角度滚动到动态创建的元素

时间:2019-12-28 05:43:06

标签: angular

我有一个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,那么我会找回元素-我怀疑问题在于元素是动态创建的吗?

1 个答案:

答案 0 :(得分:1)

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

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

最后,您可以在任何项目的scrollIntoView上使用nativeElement滚动到它:

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,因为一旦获得数据,该列表将不会呈现。因此,renderedUsers初始化之前会稍有延迟。

因此在ngOnDestroy中,请确保通过调用clearTimeout(this.timeoutId);

清除超时
  

这是您推荐的Working Sample Demo ?

相关问题