Angular Lifecycle Hooks
Angular Lifecycle Hooks
A component instance has a lifecycle that starts when Angular instantiates the
component class and renders the component view and its child views. The lifecycle
continues with change detection, as Angular checks when data-bound properties
change and updates both view and component instances as needed.
The lifecycle ends when Angular destroys the component instance and removes its
rendered template from the DOM. Directives have a similar lifecycle, as Angular
creates, updates, and destroys instances in execution.
Your application can use lifecycle hook methods to tap into key events in a
component's lifecycle or instruct new instances to start, start detecting changes
when needed, update during deployment, and clean up the instances before deleting
them
Angular manages components and directives for us when it creates them, updates
them, or destroys them. With lifecycle hooks, we can gain better control of our
application.
To do this, we add some specific hook methods prefixed with ng to our component or
directive. These hooks are split into two types:
hooks for components or directives and hooks for child components.
These are the hooks for components or directives, in call order:
constructor()
OnChanges
OnInit
DoCheck
OnDestroy
And these are the hooks for a component’s children components:
AfterContentInit
AfterContentChecked
AfterViewInit
AfterViewChecked
Below is a summary of the Angular lifecycle hooks in a table:
OnChanges
OnInit
Called on initialization
DoCheck
OnDestroy
AfterContentInit
AfterContentChecked
AfterViewChecked