Angular Component Lifecycle 🎯

beginner
24 min

Angular Component Lifecycle 🎯

Welcome back, future Angular developers! Today, we're diving into a crucial aspect of Angular: Component Lifecycle. Understanding component lifecycle will help you manage and optimize your Angular applications effectively. Let's get started!

What is Component Lifecycle? 📝

In Angular, a component's lifecycle refers to the sequence of events, from creation to destruction, that a component goes through during its lifetime. Knowing about these events can help you handle data, manage subscriptions, and optimize your application's performance.

Phases of Component Lifecycle 📝

A component's lifecycle consists of three main phases:

  1. Creation Phase - Before an Angular component is inserted into the DOM, it goes through the creation phase. During this phase, the component's constructor, ngOnChanges(), and ngOnInit() methods are executed.

  2. Stable Phase - After the component is inserted into the DOM, it enters the stable phase. During this phase, the ngDoCheck() method can be executed.

  3. Destruction Phase - When the component is about to be removed from the DOM, it goes through the destruction phase. During this phase, the ngOnDestroy() method is executed.

Let's take a closer look at each method.

Constructor 📝

The constructor is called when a new component instance is created. Use the constructor to initialize your component's properties and subscribe to any services or data sources.

ngOnChanges() 📝

The ngOnChanges() method is called when the input properties of a component change. This method allows you to react to changes in the component's inputs.

ngOnInit() 📝

The ngOnInit() method is called after the constructor and ngOnChanges(), and it's the perfect place to initialize any data that requires the component's inputs or dependencies.

ngDoCheck() 📝

The ngDoCheck() method is called whenever Angular checks for changes in the component and its children. Use this method to implement custom change detection strategies or to optimize performance.

Example 💡

Here's a simple example of a HelloComponent that demonstrates the use of the constructor, ngOnInit(), and ngOnChanges().

typescript
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-hello', template: ` <h1>Hello, {{ name }}!</h1> ` }) export class HelloComponent { @Input() name: string; constructor() { console.log('Component created!'); } ngOnInit() { console.log('Initialization complete!'); } ngOnChanges() { console.log(`Name changed to ${this.name}!`); } }

quiz

Question: What method is called when a component's input properties change?

A: constructor B: ngOnChanges() C: ngOnInit() Correct: B Explanation: The ngOnChanges() method is called when a component's input properties change.


ngAfterContentInit() 📝

The ngAfterContentInit() method is called after the component's content projects. Use this method to initialize any content projection, such as content in ng-content.

ngAfterContentChecked() 📝

The ngAfterContentChecked() method is called after Angular checks the component's content and its children for changes. Use this method to implement custom content change detection strategies or to optimize performance.

ngAfterViewInit() 📝

The ngAfterViewInit() method is called after the component's views (child components, templates, and content) have been initialized. Use this method to manipulate the component's child components or views.

ngAfterViewChecked() 📝

The ngAfterViewChecked() method is called after Angular checks the component's views and their children for changes. Use this method to implement custom view change detection strategies or to optimize performance.

ngOnDestroy() 📝

The ngOnDestroy() method is called before a component is destroyed and removed from the DOM. Use this method to unsubscribe from any subscriptions or clean up any resources.

Example 💡

Here's an updated example of a HelloComponent that demonstrates the use of the ngAfterContentInit(), ngAfterViewInit(), and ngOnDestroy() methods.

typescript
import { Component, ContentChild, ViewChild } from '@angular/core'; @Component({ selector: 'app-hello', template: ` <ng-content></ng-content> ` }) export class HelloComponent { @ContentChild('header') header; @ViewChild('message') message; constructor() { console.log('Component created!'); } ngAfterContentInit() { console.log(`Header content: ${this.header.toString()}`); } ngAfterViewInit() { console.log(`Message content: ${this.message.nativeElement.textContent}`); } ngOnDestroy() { console.log('Component destroyed!'); } }

In this example, the component has a content child named 'header' and a view child named 'message'. When the content is initialized, the ngAfterContentInit() method is called. When the view is initialized, the ngAfterViewInit() method is called. Finally, when the component is destroyed, the ngOnDestroy() method is called.


That's it for today! Understanding the component lifecycle will help you write more efficient and maintainable Angular applications. Remember, the key to mastering Angular is to practice, practice, practice!

Stay tuned for more in-depth Angular tutorials here at CodeYourCraft. Happy coding! 💡🎯