繁体   English   中英

角度等待直到绑定完成

[英]Angular wait until binding complete

为了在视图初始化完成后滚动到列表的元素,我尝试获取将通过HTTP调用后由“ * ngFor ”放入DOM的元素的getElementById

但是getElementById始终返回null,直到我用3sec的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);

  }

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

在此处找到有关离子生命周期事件的更多信息

如果用例位于页面的子组件中,则不能直接使用离子生命周期事件,而要使用@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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM