Bird
Raised Fist0
Angularframework~5 mins

Component lifecycle overview in Angular

Choose your learning style10 modes available
Introduction

Understanding the component lifecycle helps you know when and how your Angular component starts, updates, and ends. This lets you run code at the right time to make your app work smoothly.

You want to run code when a component first appears on the screen.
You need to update something when input data changes.
You want to clean up resources when a component is removed.
You want to react to changes in the component's view or content.
You want to perform actions after Angular has checked the component's data.
Syntax
Angular
import { Component, OnInit, OnChanges, OnDestroy, AfterViewInit, AfterContentInit } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `<p>Example works!</p>`,
  standalone: true
})
export class ExampleComponent implements OnInit, OnChanges, AfterViewInit, AfterContentInit, OnDestroy {

  ngOnChanges() {
    // Called when input properties change
  }

  ngOnInit() {
    // Called once after first ngOnChanges
  }

  ngAfterContentInit() {
    // Called after content (ng-content) is projected
  }

  ngAfterViewInit() {
    // Called after component's view is initialized
  }

  ngOnDestroy() {
    // Called just before component is destroyed
  }
}

Each lifecycle method runs at a specific time during the component's life.

Implement only the lifecycle hooks you need for your component.

Examples
Runs code once when the component is ready.
Angular
export class MyComponent implements OnInit {
  ngOnInit() {
    console.log('Component initialized');
  }
}
Runs code whenever input properties change.
Angular
export class MyComponent implements OnChanges {
  ngOnChanges() {
    console.log('Input changed');
  }
}
Runs cleanup code when the component is removed.
Angular
export class MyComponent implements OnDestroy {
  ngOnDestroy() {
    console.log('Component destroyed');
  }
}
Sample Program

This component logs messages when it initializes, when its input changes, and when it is destroyed. It shows how lifecycle hooks help track component events.

Angular
import { Component, Input, OnInit, OnChanges, OnDestroy, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-lifecycle-demo',
  template: `<p>Message: {{message}}</p>`,
  standalone: true
})
export class LifecycleDemoComponent implements OnInit, OnChanges, OnDestroy {
  @Input() message = '';

  ngOnChanges(changes: SimpleChanges) {
    console.log('ngOnChanges called:', changes);
  }

  ngOnInit() {
    console.log('ngOnInit called');
  }

  ngOnDestroy() {
    console.log('ngOnDestroy called');
  }
}
OutputSuccess
Important Notes

ngOnChanges runs before ngOnInit and whenever input properties change.

ngOnDestroy is useful to stop timers or unsubscribe from data streams.

Not all lifecycle hooks are needed in every component.

Summary

Angular components have special methods called lifecycle hooks.

These hooks run at key moments like creation, update, and destruction.

Use lifecycle hooks to run your code at the right time in the component's life.

Practice

(1/5)
1. Which Angular lifecycle hook is called once after the component's data-bound properties have been initialized?
easy
A. ngOnInit()
B. ngOnDestroy()
C. ngAfterViewInit()
D. ngDoCheck()

Solution

  1. Step 1: Understand lifecycle hook purpose

    ngOnInit() runs once after Angular sets component input properties.
  2. Step 2: Compare other hooks

    ngOnDestroy() runs before component removal, ngAfterViewInit() after view initialization, ngDoCheck() on every change detection.
  3. Final Answer:

    ngOnInit() -> Option A
  4. Quick Check:

    Initialization hook = ngOnInit() [OK]
Hint: Initialization after inputs = ngOnInit() [OK]
Common Mistakes:
  • Confusing ngOnInit with ngAfterViewInit
  • Thinking ngOnDestroy runs on init
  • Mixing ngDoCheck with ngOnInit
2. Which of the following is the correct syntax to implement the OnDestroy lifecycle hook in an Angular component?
easy
A. class MyComponent implements OnDestroy { ngDestroy() { } }
B. class MyComponent implements OnDestroy { ngOnDestroy() { } }
C. class MyComponent { onDestroy() { } }
D. class MyComponent implements OnDestroy { destroy() { } }

Solution

  1. Step 1: Recall correct method name

    The lifecycle hook method for destruction is ngOnDestroy().
  2. Step 2: Check interface implementation

    Implementing OnDestroy requires defining ngOnDestroy() exactly.
  3. Final Answer:

    class MyComponent implements OnDestroy { ngOnDestroy() { } } -> Option B
  4. Quick Check:

    OnDestroy method = ngOnDestroy() [OK]
Hint: Method name must be ngOnDestroy() exactly [OK]
Common Mistakes:
  • Using wrong method name like ngDestroy or destroy
  • Not implementing the interface
  • Omitting parentheses in method
3. Given this Angular component code snippet, what will be logged to the console when the component is initialized and then destroyed?
export class SampleComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('Init');
  }
  ngOnDestroy() {
    console.log('Destroy');
  }
}
medium
A. Only Destroy
B. Only Init
C. Init followed by Destroy
D. No output

Solution

  1. Step 1: Understand ngOnInit behavior

    ngOnInit() runs once when component initializes, logging 'Init'.
  2. Step 2: Understand ngOnDestroy behavior

    ngOnDestroy() runs once before component is removed, logging 'Destroy'.
  3. Final Answer:

    Init followed by Destroy -> Option C
  4. Quick Check:

    Init then Destroy logs = Init followed by Destroy [OK]
Hint: Init logs on start, Destroy logs on removal [OK]
Common Mistakes:
  • Assuming ngOnDestroy runs on init
  • Expecting logs in reverse order
  • Thinking no logs appear
4. Identify the error in this Angular component lifecycle hook implementation:
export class TestComponent implements OnInit {
  ngOnInit() {
    console.log('Component initialized');
  }
  ngOnDestroy() {
    console.log('Component destroyed');
  }
}
medium
A. Missing OnDestroy interface in implements clause
B. ngOnInit method name is incorrect
C. ngOnDestroy should not be used here
D. Console.log statements are invalid

Solution

  1. Step 1: Check implemented interfaces

    The class implements OnInit but defines ngOnDestroy() without implementing OnDestroy.
  2. Step 2: Understand interface contract

    To use ngOnDestroy(), the class should implement OnDestroy interface for clarity and correctness.
  3. Final Answer:

    Missing OnDestroy interface in implements clause -> Option A
  4. Quick Check:

    Implement interface for each lifecycle hook used [OK]
Hint: Implement interfaces for all lifecycle hooks used [OK]
Common Mistakes:
  • Ignoring interface implementation for ngOnDestroy
  • Thinking method names are wrong
  • Believing console.log is invalid
5. You want to run code after Angular fully initializes the component's view and its child views. Which lifecycle hook should you use, and why? Choose the correct hook and reason.
hard
A. ngAfterContentInit() because it runs after projected content is initialized.
B. ngOnInit() because it runs after input properties are set.
C. ngDoCheck() because it runs on every change detection cycle.
D. ngAfterViewInit() because it runs after the component's view and child views are initialized.

Solution

  1. Step 1: Identify hook for view initialization

    ngAfterViewInit() runs after Angular initializes the component's view and child views.
  2. Step 2: Compare other hooks

    ngOnInit() runs earlier, ngAfterContentInit() runs after projected content, and ngDoCheck() runs repeatedly.
  3. Final Answer:

    ngAfterViewInit() because it runs after the component's view and child views are initialized. -> Option D
  4. Quick Check:

    View init completion = ngAfterViewInit() [OK]
Hint: Use ngAfterViewInit() for post-view initialization code [OK]
Common Mistakes:
  • Confusing ngAfterContentInit with ngAfterViewInit
  • Using ngOnInit for view-dependent code
  • Expecting ngDoCheck to run once
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard