Lifecycle methods in Angular

Damaris Göbel
2 min readMar 23, 2023

--

A component instance has a lifecycle that starts when Angular instantiates the component class and renders the component view along with its child views. The lifecycle continues with change detection, as Angular checks to see when data-bound properties change, and updates both the view and the component instance as needed. The lifecycle ends when Angular destroys the component instance and removes its rendered template from the DOM.

The lifecycle hooks give you the opportunity to act on a component or directive instance at the appropriate moment, as Angular creates, updates, or destroys that instance

ngOnInit()

the OnInit interface has a hook method named ngOnInit()

If you implement this method in your component or directive class, Angular calls it shortly after checking the input properties for that component or directive for the first time.

ngOnChanges()

Respond when Angular sets or resets data-bound input properties. The method receives a SimpleChanges object of current and previous property values.

Called before ngOnInit() (if the component has bound inputs) and whenever one or more data-bound input properties change.

ngDoCheck()

Detect and act upon changes that Angular can’t or won’t detect on its own.

Called immediately after ngOnChanges() on every change detection run, and immediately after ngOnInit() on the first run.

ngAfterContentInit()

Respond after Angular projects external content into the component’s view, or into the view that a directive is in.

Called once after the first ngDoCheck().

ngAfterContentChecked()

Respond after Angular checks the content projected into the directive or component.

Called after ngAfterContentInit() and every subsequent ngDoCheck()

ngAfterViewInit()

Respond after Angular initializes the component’s views and child views, or the view that contains the directive.

Called once after the first ngAfterContentChecked().

ngAfterViewChecked()

Respond after Angular checks the component’s views and child views, or the view that contains the directive

Called after the ngAfterViewInit() and every subsequent ngAfterContentChecked()

ngOnDestroy()

Cleanup just before Angular destroys the directive or component. Unsubscribe Observables and detach event handlers to avoid memory leaks.

Called immediately before Angular destroys the directive or component.

--

--

Damaris Göbel

I like to do crazy things with CSS & JavaScript. My brain occasionally runs out of memory so I need to write down my thoughts.