Angular Tutorial: Component Lifecycle Hooks 🎯

beginner
20 min

Angular Tutorial: Component Lifecycle Hooks 🎯

Welcome back! In our ongoing journey through the world of Angular, today we're diving deep into a fascinating topic - Component Lifecycle Hooks. These are special functions that we can add to our Angular components to interact with their lifecycle events. Let's get started!

Understanding Component Lifecycle 📝

Before we dive into the hooks, let's clarify what we mean by a component's lifecycle. It refers to the sequence of stages that an Angular component goes through, from its creation to its destruction.

Introduction to Lifecycle Hooks 💡

Angular provides us with several lifecycle hooks that allow us to execute custom code at specific points during a component's lifecycle. These hooks are nothing but special methods that we can add to our components.

The Lifecycle Hooks ✅

Angular provides 7 lifecycle hooks that we can use in our components. Here's a brief overview of each one:

  1. ngOnChanges - Triggers when input properties are changed.
  2. onInit - Triggers immediately after the component's properties are initialized.
  3. doCheck - Triggers when Angular checks the component's property to see if it needs to re-render.
  4. ngAfterContentInit - Triggers after the component's content has been initialized.
  5. ngAfterContentChecked - Triggers after Angular checks the component's content to see if it needs to re-render.
  6. ngAfterViewInit - Triggers after the component's view (or views) has been initialized.
  7. ngAfterViewChecked - Triggers after Angular checks the component's view (or views) to see if it needs to re-render.

A Practical Example 🎯

Let's create a simple component and add a lifecycle hook to demonstrate its functionality.

typescript
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-example', template: ` <h1>{{ message }}</h1> `, }) export class ExampleComponent implements OnInit { message = 'Hello, World!'; constructor() {} ngOnInit() { console.log('Component created!'); this.message = 'Angular Rocks!'; } }

In this example, we've added the OnInit hook to our component. When this component is created, the ngOnInit method is called, which allows us to initialize our component's properties and execute any other code we need to run upon creation.

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the `OnInit` lifecycle hook?

Stay tuned for our next lesson, where we'll delve deeper into these lifecycle hooks and see how we can use them to create even more powerful Angular applications! 🎯