ngOnInit ()、ngAfterViewInit ()、ngafterContentInit ()、ngAfterViewChecked ()和构造函数()有什么区别?我们如何在 Angular 2 中实现它们?它们的用途和用途是什么?它在哪里对实施它们有用?
谢谢。
ngOnInit ()、ngAfterViewInit ()、ngafterContentInit ()、ngAfterViewChecked ()和构造函数()有什么区别?我们如何在 Angular 2 中实现它们?它们的用途和用途是什么?它在哪里对实施它们有用?
谢谢。
这些是生命周期钩子,您可以利用它们来执行操作和组件生命周期的不同时间。
官方 Angular 文档中有关于该主题的优秀指南:https ://angular.io/guide/lifecycle-hooks
组件的生命周期由 Angular 管理。
Angular 创建它,渲染它,创建和渲染它的子节点,当它的数据绑定属性发生变化时检查它,并在从 DOM 中删除它之前销毁它。
Angular 提供了生命周期钩子,可以提供对这些关键生命时刻的可见性以及在它们发生时采取行动的能力。
官方文档中的下图描述了生命周期钩子的顺序:
constructor
It's a class constructor that is triggered when Angular instantiates components. It's mostly used for DI and is called before Angular runs change detection. You can read more about it here:
ngOnInit(), ngAfterViewInit(), ngafterContentInit(), ngAfterViewChecked()
These are lifecycle hooks. They differ in the timing they are called and hence the data that is available in each of them. The timing with regards to other operations in change detection is clearly shown in the article:
Everything you need to know about change detection in Angular
The order is clearly defined:
OnChanges
lifecycle hook on a child component if bindings changedNotifies whenever there's a change in the @Input
bindings. Use it if you need constantly to track these bindings.
OnInit
and ngDoCheck
on a child component (OnInit
is called only during first check)Notifies that @Input
bindings are available. Use it if you don't need to constantly track these bindings.
AfterContentInit
and AfterContentChecked
lifecycle hooks on child component instance (AfterContentInit
is called only during first check)Notifies that Angular ran change detection for the projected content (ng-content). Use it if you need to query projected elements using @ContentChildren
decorator.
AfterViewInit
and AfterViewChecked
lifecycle hooks on child component instance (AfterViewInit
is called only during first check)Notifies that Angular ran change detection for the view content. Use it if you need to query view elements using @ViewChildren
decorator.
There's a lot of confusion about ngDoCheck
lifecycle hook. To understand more read If you think ngDoCheck
means your component is being checked — read this article.