所有孩子都初始化后,Angular 2生命周期挂钩? [英] Angular 2 life cycle hook after all children are initialized?

查看:61
本文介绍了所有孩子都初始化后,Angular 2生命周期挂钩?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种实现以下情况的概念:

I am looking for a concept to implement the following case:

我有一个父级搜索组件,其中有一些组件,例如视图子级/内容子级,用于显示构面和搜索结果.现在,我想在应用程序完成加载后触发搜索,以使用户看不到空白页.

I have a parent search component that has some components as view children / content children for displaying facets and search results. I now want to trigger a search when the application has finished loading so the user does not see an empty page.

我现在的问题是我找不到适合自己需求的生命周期挂钩.构面/搜索结果在其各自的ngOnInit中订阅搜索结果.因此,我需要一个在所有子组件都完成初始化之后被称为 的钩子.

My problem now is that I cannot find a lifecycle hook that fits my needs. The facets / search results subscribe to the search results in their respective ngOnInit. So I need a hook that gets called after all child components had finished initializing.

我在父组件上尝试了以下钩子

I have tried the following hooks on the parent component

  • ngAfterContentInit :在子元素上调用ngOnInit之前先调用它
  • ngAfterViewInit :该方法有效,但是在搜索结果返回后,子视图的视图将更新,这会导致错误,因为在 ngAfterViewInit
  • ngAfterContentInit: this gets called before ngOnInit is called on the children
  • ngAfterViewInit: this one works but after the search results return the view of the children gets updated which leads to an error since actions that manipulate the view are not allowed in ngAfterViewInit

任何想法如何解决这个问题?在我看来,我似乎并没有掌握一些基本知识.

Any Idea how to tackle this problem? To me it seems I do not grasp something fundamental here.

欢呼

汤姆

推荐答案

我最终通过以下方式使用ngAfterViewInit()挂钩:

I ended up using the ngAfterViewInit() hook in the following way:

ngAfterViewInit(){
  //stuff that doesn't do view changes
  setTimeout(_=> this.methodThatKicksOffAnotherRoundOfChanges());
}

与设置实际时间的其他setTimeout调用相比,此方法应该安全使用,因为它应该立即启动(并且只会影响线程/上下文行为)

This should be safe to use compared to other invocations of setTimeout where an actual time is set, since it should start instantly (and just affect the threading/context behaviour)

这篇关于所有孩子都初始化后,Angular 2生命周期挂钩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆