问题
What is the difference between ngOnInit(), ngAfterViewInit(), ngafterContentInit(), ngAfterViewChecked() and a constructor()? How do we implement them in the Angular 2? What are their purposes and usages? Where all will it be useful for implementing them?
Thanks.
回答1:
Those are life cycle hooks that you can tap into to perform operations and different times of a components life cycle.
There is an excellent guide on the topic in the official angular documentation: https://angular.io/guide/lifecycle-hooks
A component has a lifecycle managed by Angular.
Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change, and destroys it before removing it from the DOM.
Angular offers lifecycle hooks that provide visibility into these key life moments and the ability to act when they occur.
The following diagram from the official documentation describes the order of lifecycle hooks:
回答2:
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:
- The essential difference between Constructor and ngOnInit in Angular
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 changed
Notifies whenever there's a change in the @Input
bindings. Use it if you need constantly to track these bindings.
OnInit
andngDoCheck
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
andAfterContentChecked
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
andAfterViewChecked
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.
来源:https://stackoverflow.com/questions/46314734/what-is-the-difference-between-ngoninit-ngafterviewinit-ngaftercontentinit