</>
Skip to content
Angular lessons (30/43)

Angular — Lifecycle

Lifecycle Hooks

HookWhen Called
constructorClass instantiation
ngOnInitAfter first ngOnChanges
ngOnChangesWhen input properties change
ngDoCheckCustom change detection
ngAfterContentInitContent projected
ngAfterContentCheckedContent checked
ngAfterViewInitView initialized
ngAfterViewCheckedView checked
ngOnDestroyBefore destruction

Example

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

@Component({
  selector: 'app-lifecycle',
  template: `<p>{{message}}</p>`
})
export class LifecycleComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {
  @Input() data: any;
  message = 'Hello';
  
  constructor() {
    console.log('Constructor');
  }
  
  ngOnChanges(changes: SimpleChanges) {
    console.log('Changes:', changes);
  }
  
  ngOnInit() {
    console.log('Initialized');
  }
  
  ngAfterViewInit() {
    console.log('View ready');
  }
  
  ngOnDestroy() {
    console.log('Destroyed');
  }
}

Common Use Cases

HookUse Case
ngOnInitFetch data, initialize
ngOnChangesReact to input changes
ngOnDestroyCleanup subscriptions
ngAfterViewInitAccess child components

Mini Practice

  1. Implement all lifecycle hooks
  2. Log lifecycle events
  3. Fetch data in ngOnInit
  4. Clean up in ngOnDestroy

Up Next

Continue with Composition API — Angular composition patterns.

Related Topics

Frequently Asked Questions about Lifecycle

What is Lifecycle in Angular?

Lifecycle is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Lifecycle?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Lifecycle.

Why is Lifecycle important in Angular?

Lifecycle is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.