angular - Angular 等到绑定完成
问题描述
为了在视图初始化完成后滚动到列表的元素,我试图在进行HTTP调用后通过“ *ngFor ”将元素的getElementById放入 DOM ,
但是getElementById总是返回null,直到我用3秒的setTimeout包围它,所以它返回元素。
所以我正在寻找一个干净的解决方案,等到绑定到视图中完成,然后再制作 getElementById。
组件.ts:
InitDisponibilites(disponibilites) {
this.disponibilites = Array();
for (let disponibilite of disponibilites) {
this.addDisponibilite(disponibilite);
}
setTimeout(()=>{
let index = this.getElementIndexToScroll();
let el = document.getElementById('dispo' + index) as HTMLElement;
el.scrollIntoView();
},3000);
}
解决方案
您可以将该代码移动到ionViewDidEnter
方法ionViewWillEnter
中,这些事件是基于离子生命周期调用的。您可以选择两者中的任何一个,这取决于您想要滚动效果的时间。
在此处查找有关离子生命周期事件的更多信息
如果您的用例位于页面的子组件中,那么您不能直接使用离子生命周期事件,而是使用@ViewChild
访问要使用页面事件调用的组件方法。
@ViewChild(childComponent) childComponent: ChildComponent;
----------------------
----bunch of code ----
----------------------
ionViewWillEnter() {
this.childComponent.willEnter(); //scroll logic will go inside the willEnter method.
}
更新
如果您要填充子组件作为对 http 的响应,您可以尝试使用与组件关联的 Angular 生命周期事件ngAfterViewInit()
,然后检查给定的组件索引是否是所需的索引,将其滚动到视图中。
子组件.html
<div #rootDiv [selected]="index === getElementIndexToScroll()"></div>
子组件.ts
export class ChildComponent implements AfterViewInit {
@ViewChild('rootDiv') rootElement: ElementRef;
@Input() selected: boolean;
ngAfterViewInit() {
if (this.selected) {
this.rootElement.nativeElement.scrollIntoView();
}
}
推荐阅读
- android - IP Cam 流加载如此缓慢
- python-3.x - Google Cloud Function Python 包未通过 requirements.txt 安装
- node.js - 如何在 mongodb docker 映像中运行 nodejs 应用程序?
- ocaml - Z3Prover/z3 安装失败
- javascript - 在 Google Apps 脚本中从其他域访问 Gsuite 管理目录
- php - 为什么 laravel delete() 函数会出错?
- java - 带有对象的算术运算任务
- python - 在 Python 中使用 sklearn.linear_model.LinearRegression 时出现 ValueError
- ansible - 替换正则表达式 Ansible 中的嵌套变量 [模板错误
- kubernetes - 在 kops 部署的 AWS k8s 集群中,我应该使用哪个入口控制器来支持 WebSocket?