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,那么我会取回元素 - 我怀疑问题是元素是动态创建的?
解决方案
您可以将模板变量分配给列表项:
<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
a nativeElement
of 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);
这是您的参考的工作示例演示。
推荐阅读
- google-compute-engine - 通过 Compute Engine VM 的默认凭据使用 GAM(Google Apps Manager)
- linux - 如何从 linux 终端中删除错误?
- c# - 无法以正确的方式反序列化我的 xml 文件。总是为空
- angular - 'mat-expansion-panel' 不是已知元素
- linux - 为什么从 shell 脚本运行的进程的父 ID 为 1
- c# - 使用查找运算符的单个元素
- arrays - Python3 | 课程 | 面向对象
- java - junit jupiter 运行配置
- javascript - Angularjs自定义三态开关切换与布局问题内的材料按钮
- reactjs - 为所有孩子添加道具价值和财产