简体   繁体   English

角度等待直到绑定完成

[英]Angular wait until binding complete

In the purpose of scrolling to an element of a list after the view initialization completes, I'm trying to getElementById of an element that will be put into the DOM by an " *ngFor " after making an HTTP call, 为了在视图初始化完成后滚动到列表的元素,我尝试获取将通过HTTP调用后由“ * ngFor ”放入DOM的元素的getElementById

But the getElementById always returned null until I surround it with a setTimeout of 3sec, so it returns the element. 但是getElementById始终返回null,直到我用3sec的setTimeout包围它为止,因此它返回元素。

So I'm searching for a clean solution to wait until the binding into the view completes before I make getElementById. 因此,我正在寻找一种干净的解决方案,以等待与视图的绑定完成之后再创建getElementById。

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

  }

You can move that code either into ionViewDidEnter or ionViewWillEnter methods, those events are called based on ionic lifecycle. 您可以将该代码移动到ionViewDidEnterionViewWillEnter方法中,这些事件基于离子生命周期进行调用。 You can choose any of the two, depends on how soon you want the scroll effect. 您可以选择二者之一,具体取决于您希望滚动效果多久。

Find more about ionic lifecycle events here 在此处找到有关离子生命周期事件的更多信息

If your use case lies in the subcomponent of a page, then you can't use ionic lifecycle event directly, instead use @ViewChild to access your component method to be called with page event. 如果用例位于页面的子组件中,则不能直接使用离子生命周期事件,而要使用@ViewChild访问要通过页面事件调用的组件方法。

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

UPDATES 更新
If you are populating the child components as response to http, you can try using angular lifecycle event associated with the component ngAfterViewInit() , then check if given component index is the desired index, scroll it into the view. 如果要填充子组件作为对http的响应,则可以尝试使用与组件ngAfterViewInit()关联的角度生命周期事件,然后检查给定的组件索引是否为所需的索引,将其滚动到视图中。

childcomponent.html childcomponent.html

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

childcomponent.ts 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