角度等待直到绑定完成

时间:2019-08-23 16:32:29

标签: angular ionic-framework ionic3 angular5

为了在视图初始化完成之后滚动到列表的元素,我试图 getElementById ,该元素将由“ *”放入DOM ngFor ”,然后进行 HTTP 调用

但是getElementById总是返回 null ,直到我用3秒的 setTimeout 将其包围起来,因此它会返回元素。

因此,我正在寻找一种干净的解决方案,直到等到视图绑定完成之后,再创建getElementById。

component.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);

  }

1 个答案:

答案 0 :(得分:0)

您可以将该代码移动到ionViewDidEnterionViewWillEnter方法中,这些事件基于离子生命周期进行调用。您可以选择两者中的任意一个,具体取决于您希望滚动效果多久。

进一步了解离子生命周期事件here

如果用例位于页面的子组件中,则不能直接使用离子生命周期事件,而应使用@ViewChild访问要通过页面事件调用的组件方法。

@ViewChild(childComponent) childComponent: ChildComponent;
----------------------
----bunch of code ----
----------------------
ionViewWillEnter() {
    this.childComponent.willEnter(); //scroll logic will go inside the willEnter method.
}

更新
如果要填充子组件作为对http的响应,则可以尝试使用与组件ngAfterViewInit()关联的角度生命周期事件,然后检查给定的组件索引是否为所需的索引,将其滚动到视图中。

childcomponent.html

<div #rootDiv [selected]="index === getElementIndexToScroll()"></div>

childcomponent.ts

export class ChildComponent implements AfterViewInit {
   @ViewChild('rootDiv') rootElement: ElementRef;
   @Input() selected: boolean;

  ngAfterViewInit() {
    if (this.selected) {
       this.rootElement.nativeElement.scrollIntoView();
    }
}