【问题标题】:Notice when angular component and its children are rendered注意何时渲染角度组件及其子项
【发布时间】:2018-11-14 13:35:52
【问题描述】:

我有一个角度组件,该组件具有另一个组件,该组件也具有另一个组件。所以,组件是嵌套的。

我想注意所有子组件视图何时完全呈现。 我尝试了所有的生命周期钩子,比如

ngAfterContentChecked

ngOnChanges

但他们都没有被调用。是否可以识别渲染?

编辑:

我的视图将动态更改。因此,我需要知道这一点,而不仅仅是一开始。

我的组件看起来像:

父视图:

<child-1></child-1>

Child-1 视图:

<child-2><child-2>

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    您可以确定,当最深和最后一个子组件中的ngAfterViewInit 被调用时,所有的祖先也会被渲染。

    这基本上意味着,如果你有这样的结构:

    <parent>
      <child-1>
        <child-2></child-2>
        <child-3></child-3>
      </child-1>
    </parent>
    

    您可以确定当child-3 调用ngAfterViewInit 时,树中的所有内容都会被渲染:

    @Component({
      selector: 'child-3'
    }) 
    export class Child3Component implements AfterViewInit {
      ngAfterViewInit(): void {
        console.log('all done here');
      }
    }
    

    如果你想知道什么时候通过树处理更新以及模板在一个周期后更新,你需要使用ngAfterViewChecked钩子。有趣的事实是,这是相反的。所以你只需要在最父节点上监听就可以知道它什么时候完成了检查。

    记住同一棵树:

    @Component({
      selector: 'parent'
    }) 
    export class ParentComponent implements AfterViewChecked {
      ngAfterViewChecked(): void {
        console.log('all done here');
      }
    }
    

    另一方面,如果你想知道一个事件被触发后,视图是否被更新,你也可以只使用变化检测器,或者 applicationRef,或者一个 setTimeout:

    如果这部分代码在你的组件中

    (不应该!不要在组件内部直接使用http!)

    this.http.get(url).subscribe((data) => {
      this.data = data;
    
      // method 1:
      setTimeout(() => {
        // view is rendered here
      });
    
    
      // method 2:
      this.changeDetectorRef.detectChanges();
      // view is rendered here
    
    
      // method 3:
      this.applicationRef.tick();
      // view is rendered here
    }); 
    

    但请注意,如果您的组件(或任何父组件)将 changeDetection 设置为 OnPush,您首先必须使用任何方法设置:this.changeDetectorRef.markForCheck()

    【讨论】:

    • 谢谢。我忘了说我动态更新了视图。那么ngAfterViewInit 也会被调用吗?
    • @chocolatecake 啊,所以你想知道模板中的更新什么时候处理?
    • 是的,完全正确 :) 你是对的,它会在 http 响应后发生变化。
    • 一种方法是让孩子订阅一个可观察对象并在其“完成”时发出一个值,在一个组件中 this.obs$.emit('done') 可以在 ngAfterViewInit 上,而在另一个组件中它可以在http 通话订阅\点击。
    • this.changeDetectorRef.detectChanges(); 在正确的位置就可以了。感谢@PierreDuc 的大力帮助、时间和精彩的解释!!!
    猜你喜欢
    • 1970-01-01
    • 2021-03-05
    • 2017-03-08
    • 2018-03-16
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 2021-05-08
    相关资源
    最近更新 更多