首页 > 解决方案 > 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);

  }

标签: angularionic-frameworkionic3angular5

解决方案


您可以将该代码移动到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();
    }
}

推荐阅读