Tutorials Logic, IN info@tutorialslogic.com

Angular Lifecycle Hooks ngOnInit to Destroy

Angular Lifecycle Hooks ngOnInit to Destroy

Angular Lifecycle Hooks ngOnInit to Destroy is an important Angular topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

For this page, focus on what problem Angular Lifecycle Hooks ngOnInit to Destroy solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .

A strong understanding of Angular Lifecycle Hooks ngOnInit to Destroy should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.

Angular Lifecycle Hooks ngOnInit to Destroy should be studied as a practical Angular lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the angular > lifecycle-hooks page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

What are Lifecycle Hooks?

Angular calls lifecycle hook methods at specific moments in a component's life - from creation to destruction. Implementing these interfaces lets you tap into those moments to run your own logic.

Lifecycle Sequence

Hook When it runs Common use
ngOnChanges() Before ngOnInit, every time an @Input changes React to input changes
ngOnInit() Once, after first ngOnChanges Fetch data, initialize state
ngDoCheck() Every change detection cycle Custom change detection
ngAfterContentInit() Once, after content projection Access @ContentChild
ngAfterContentChecked() After every content check Respond to projected content changes
ngAfterViewInit() Once, after view & child views init Access @ViewChild, DOM manipulation
ngAfterViewChecked() After every view check Respond to view changes
ngOnDestroy() Just before component is destroyed Unsubscribe, cleanup timers

ngOnInit - Most Common Hook

ngOnInit

ngOnInit
import { Component, OnInit, inject, signal } from '@angular/core';
import { UserService } from './user.service';

@Component({
    selector: 'app-user',
    standalone: true,
    template: `
        @if (user()) {
            <h2>{{ user()!.name }}</h2>
        } @else {
            <p>Loading...</p>
        }
    `
})
export class UserComponent implements OnInit {
    private userService = inject(UserService);
    user = signal<any>(null);

    ngOnInit() {
        // Runs once after component is initialized
        // Inputs are available here (unlike the constructor)
        this.userService.getUser(1).subscribe(u => this.user.set(u));
    }
}

ngOnChanges - Reacting to Input Changes

ngOnChanges

ngOnChanges
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
    selector: 'app-child',
    standalone: true,
    template: `<p>{{ title }}</p>`
})
export class ChildComponent implements OnChanges {
    @Input() title = '';
    @Input() count = 0;

    ngOnChanges(changes: SimpleChanges) {
        if (changes['title']) {
            const prev = changes['title'].previousValue;
            const curr = changes['title'].currentValue;
            console.log(`title changed: ${prev} -> ${curr}`);
        }
        if (changes['count']?.firstChange) {
            console.log('count set for the first time:', this.count);
        }
    }
}
// Note: with signal-based input(), use effect() instead of ngOnChanges

ngOnDestroy - Cleanup

ngOnDestroy

ngOnDestroy
import { Component, OnInit, OnDestroy, signal } from '@angular/core';
import { Subscription, interval } from 'rxjs';

@Component({
    selector: 'app-timer',
    standalone: true,
    template: `<p>Elapsed: {{ seconds() }}s</p>`
})
export class TimerComponent implements OnInit, OnDestroy {
    seconds = signal(0);
    private sub!: Subscription;

    ngOnInit() {
        this.sub = interval(1000).subscribe(() => {
            this.seconds.update(s => s + 1);
        });
    }

    ngOnDestroy() {
        // ALWAYS unsubscribe to prevent memory leaks
        this.sub.unsubscribe();
        console.log('TimerComponent destroyed, subscription cleaned up');
    }
}

ngAfterViewInit - Accessing the DOM

ngAfterViewInit

ngAfterViewInit
import { Component, AfterViewInit, viewChild, ElementRef } from '@angular/core';

@Component({
    selector: 'app-focus',
    standalone: true,
    template: `<input #nameInput type="text" placeholder="Auto-focused" />`
})
export class FocusComponent implements AfterViewInit {
    // Signal-based ViewChild (Angular 17+)
    nameInput = viewChild.required<ElementRef>('nameInput');

    ngAfterViewInit() {
        // DOM is fully rendered - safe to access elements
        this.nameInput().nativeElement.focus();
    }
}

Modern Alternative: effect() with Signals

With signal-based inputs (input()), you can use effect() instead of ngOnChanges for a cleaner reactive approach.

effect() vs ngOnChanges

effect() vs ngOnChanges
import { Component, input, effect, computed } from '@angular/core';

@Component({
    selector: 'app-modern',
    standalone: true,
    template: `<p>{{ greeting() }}</p>`
})
export class ModernComponent {
    name = input.required<string>();

    greeting = computed(() => `Hello, ${this.name()}!`);

    constructor() {
        // Runs whenever name() changes - replaces ngOnChanges
        effect(() => {
            console.log('Name changed to:', this.name());
        });
    }
}

Detailed Learning Notes for Angular Lifecycle Hooks ngOnInit to Destroy

When studying Angular Lifecycle Hooks ngOnInit to Destroy, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.

In Angular, Angular Lifecycle Hooks ngOnInit to Destroy becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.

  • Identify the main problem this topic solves.
  • Write the smallest possible working example.
  • Change one input or option and observe the result.
  • Note the mistake that would break the example.

Angular Lifecycle Hooks ngOnInit to Destroy state check

Angular Lifecycle Hooks ngOnInit to Destroy state check
const state = { topic: "Angular Lifecycle Hooks ngOnInit to Destroy", ready: true };
if (state.ready) {
  console.log(state.topic + ": render or run the normal path");
}

Angular Lifecycle Hooks ngOnInit to Destroy fallback check

Angular Lifecycle Hooks ngOnInit to Destroy fallback check
const response = null;
const message = response?.message ?? "Angular Lifecycle Hooks ngOnInit to Destroy: show a clear fallback";
console.log(message);
Key Takeaways
  • Explain the purpose of Angular Lifecycle Hooks ngOnInit to Destroy before memorizing syntax.
  • Run or trace one small Angular example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for Angular Lifecycle Hooks ngOnInit to Destroy.
  • Write the rule in your own words after checking the example.
  • Connect Angular Lifecycle Hooks ngOnInit to Destroy to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing Angular Lifecycle Hooks ngOnInit to Destroy without the situation where it is useful.
RIGHT Connect Angular Lifecycle Hooks ngOnInit to Destroy to a concrete Angular task.
Purpose makes syntax easier to recall.
WRONG Testing Angular Lifecycle Hooks ngOnInit to Destroy only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to Angular Lifecycle Hooks ngOnInit to Destroy.
Evidence keeps debugging focused.
WRONG Memorizing Angular Lifecycle Hooks ngOnInit to Destroy without the situation where it is useful.
RIGHT Connect Angular Lifecycle Hooks ngOnInit to Destroy to a concrete Angular task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to Angular Lifecycle Hooks ngOnInit to Destroy, then fix it and explain the fix.
  • Summarize when to use Angular Lifecycle Hooks ngOnInit to Destroy and when another approach is better.
  • Write a small example that uses Angular Lifecycle Hooks ngOnInit to Destroy in a realistic Angular scenario.
  • Change one important value in the Angular Lifecycle Hooks ngOnInit to Destroy example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in Angular, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.