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

Angular 角度滚动到动态创建的元素,angular,Angular,我有一个Angular应用程序,当用户单击按钮时检索数据: getJobNotes() { this.jobNoteService.getJobNotes() .subscribe( result => { this.jobNotes = result.jobNotes; } ); } 我想滚动查看一个具有特定工作通知Id的元素,例如,这可能是10个列表中的第5个元素 我尝试了以下方法: this.selectedJobNo

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

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

<ul *ngIf="users">
  <li #user *ngFor="let userDetail of users">
    <h1>{{ userDetail.name }}</h1>
    <h2>{{ userDetail.username }}</h2>
    <h3>{{ userDetail.email }}</h3>
  </li>
</ul>
最后,您可以在任何项目的
nativeElement
上使用
scrollIntoView
,滚动到它:

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
之前会有一点延迟

因此,在
ngondestory
中,也要确保通过调用
clearTimeout(this.timeoutId)来清除超时


这是一个工作示例演示
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);
    });
}