Angular Components' Lifecycle
Introduction
Section titled âIntroductionâComponentâs lifecycle is the sequence of steps that happen between the componentâs creation and its destruction. You can implement lifecycle hooks to run code during these steps.
Lifecycle Methods
Section titled âLifecycle MethodsâAngular walks your application tree from top to bottom, checking template bindings for changes.
| Phase | Method | Summary |
| Creation | constructor | Standard JavaScript class constructor. Runs when Angular instantiates the component. |
| Change Detection | ngOnInit | Runs once after Angular has initialized all the componentâs inputs. |
ngOnChanges | Runs every time the componentâs inputs have changed. | |
ngDoCheck | Runs every time this component is checked for changes. | |
ngAfterContentInit | Runs once after the componentâs content has been initialized. | |
ngAfterContentChecked | Runs every time this component content has been checked for changes. | |
ngAfterViewInit | Runs once after the componentâs view has been initialized. | |
ngAfterViewChecked | Runs every time the componentâs view has been checked for changes. | |
| Rendering | afterNextRender | Runs once the next time that all components have been rendered to the DOM. |
afterEveryRender | Runs every time all components have been rendered to the DOM. | |
| Destruction | ngOnDestroy | Runs once before the component is destroyed. |
ngOnInit
Section titled ângOnInitângOnInit method:
- runs after Angular has initialized all the components inputs with their initial values,
- runs exactly once.
This step happens before the componentâs own template is initialized. This means that you can update the componentâs state based on its initial input values.
ngOnChanges
Section titled ângOnChangesângOnChanges method runs after any component inputs have changed.
This step happens before the componentâs own template is checked: you can update the componentâs state based on its initial input values.
During initialization, the first ngOnChanges runs before ngOnInit.
Inspecting changes
Section titled âInspecting changesângOnChanges method accepts one argument of type SimpleChanges.
This object is a Record mapping each component input name to a SimpleChange object.
Each SimpleChange contains:
- inputâs previous value,
- inputâs current value,
- a flag for whether this is the first time the input has changed.
If you provide an alias for any input properties, SimpleChanges still uses the TypeScript property name as a key, rather than the alias.
import { Component, input, SimpleChanges } from '@angular/core';
@Component({/*...*/})export class App { name = input('');
ngOnChanges(changes: SimpleChanges<App>) { if (changes.name) { console.log(`Previous: ${changes.name.previousValue}`); console.log(`Current: ${changes.name.currentValue}`); console.log(`Is first ${changes.name.firstChange}`); } }}ngOnDestroy
Section titled ângOnDestroyângOnDestroy method runs once just before a component is destroyed.
Angular destroys a component when it is no longer shown on the page (such as being hidden by @if or upon navigating to another page).
DestroyRef
Section titled âDestroyRefâInstead of using ngOnDestroy method, you can inject an instance of DestroyRef.
You can register a callback to be invoked upon the componentâs destruction by calling onDestroy method of DestroyRef.
import { Component, DestroyRef, inject } from '@angular/core';
@Component({/*...*/})export class App { constructor() { inject(DestroyRef).onDestroy(() => { console.log('App destruction'); }); }}You can pass
DestroyRefinstance to functions or classes outside your component. Use this pattern if you have other code that should run some cleanup behavior when the component is destroyed.
DestroyRef provides a destroyed property that allows checking whether a given instance has already been destroyed.
This is useful for avoiding operations on destroyed components, especially when dealing with delayed or asynchronous logic.
By checking
destroyRef.destroyed, you can prevent executing code after the instance has been cleaned up, avoiding potential errors such as NG0911: View has already been destroyed..
ngDoCheck
Section titled ângDoCheckângDoCheck method runs before Angular checks a componentâs template for changes (every time).
This method runs very frequently: it can impact your pageâs performance.
You can use this lifecycle hook to manually check for state changes outside of Angularâs normal change detection, manually updating the componentâs state.
During initialization, the first ngDoCheck runs after ngOnInit.
ngAfterContentInit
Section titled ângAfterContentInitângAfterContentInit method runs once after all the children nested inside the component (its content) have been initialized.
You can use this lifecycle hook to read the results of content queries. While you can access the initialized state of these queries, attempting to change any state in this method results in an NG0100 error.
ngAfterContentChecked
Section titled ângAfterContentCheckedângAfterContentChecked method runs every time the children nested inside the component (its content) have been checked for changes.
This method runs very frequently and can significantly impact your pageâs performance. Avoid defining this hook whenever possible, only using it when you have no alternative.
While you can access the updated state of content queries here, attempting to change any state in this method results in an NG0100 error.
ngAfterViewInit
Section titled ângAfterViewInitângAfterViewInit method runs once after all the children in the componentâs template (its view) have been initialized.
You can use this lifecycle hook to read the results of . While you can access the initialized state of view queries here, attempting to change any state in this method results in an NG0100 error.
ngAfterViewChecked
Section titled ângAfterViewCheckedângAfterViewChecked method runs every time the children in the componentâs template (its view) have been checked for changes.
This method runs very frequently and can significantly impact your pageâs performance. Avoid defining this hook whenever possible, only using it when you have no alternative.
While you can access the updated state of view queries here, attempting to change any state in this method results in an NG0100 error.
afterEveryRender and afterNextRender
Section titled âafterEveryRender and afterNextRenderâafterEveryRender and afterNextRender functions let you register a render callback to be invoked after Angular has finished rendering all components on the page into the DOM.
Rather than a class method, they are standalone functions that accept a callback. The execution of render callbacks are not tied to any specific component instance, but instead an application-wide hook.
afterEveryRender and afterNextRender must be called in an injection context, typically a componentâs constructor.
You can use render callbacks to perform manual DOM operations. See Using DOM APIs for guidance on working with the DOM in Angular.
Render callbacks do not run during server-side rendering or during build-time pre-rendering.
Lifecycle interfaces
Section titled âLifecycle interfacesâAngular provides a TypeScript interface for each lifecycle method. You can optionally import and implement these interfaces to ensure that your implementation does not have any typos or misspellings.
Each interface has the same name as the corresponding method without the ng prefix.
For example, the interface for ngOnInit is OnInit.
import { Component, input, onChanges, SimpleChanges } from '@angular/core';
@Component({/*...*/})export class App implements OnChanges { name = input('');
ngOnChanges(changes: SimpleChanges<App>) { if (changes.name) { console.log(`Previous: ${changes.name.previousValue}`); console.log(`Current: ${changes.name.currentValue}`); console.log(`Is first ${changes.name.firstChange}`); } }}Execution order
Section titled âExecution orderâThe following diagrams show the execution order of Angularâs lifecycle hooks.