Lifecycle hooks help you run code at important moments in a component's life, like when it starts or stops. This keeps your app organized and working smoothly.
Why lifecycle hooks matter in Angular
import { Component, OnInit, OnDestroy } from '@angular/core'; @Component({ selector: 'app-example', template: `<p>Example works!</p>` }) export class ExampleComponent implements OnInit, OnDestroy { ngOnInit() { // Code to run when component starts } ngOnDestroy() { // Code to run when component is removed } }
Lifecycle hooks are methods you add to your component class.
Angular calls these methods automatically at the right time.
import { OnInit } from '@angular/core'; export class MyComponent implements OnInit { ngOnInit() { console.log('Component started'); } }
import { OnDestroy } from '@angular/core'; export class MyComponent implements OnDestroy { ngOnDestroy() { console.log('Component removed'); } }
import { OnChanges, SimpleChanges } from '@angular/core'; export class MyComponent implements OnChanges { ngOnChanges(changes: SimpleChanges) { console.log('Input changed', changes); } }
This component starts a timer when it appears and stops it when removed. This prevents the timer from running forever and wasting resources.
import { Component, OnInit, OnDestroy } from '@angular/core'; @Component({ selector: 'app-timer', template: `<p>Seconds passed: {{seconds}}</p>` }) export class TimerComponent implements OnInit, OnDestroy { seconds = 0; intervalId?: number; ngOnInit() { this.intervalId = window.setInterval(() => { this.seconds++; }, 1000); } ngOnDestroy() { if (this.intervalId !== undefined) { clearInterval(this.intervalId); } } }
Always clean up in ngOnDestroy to avoid memory leaks.
ngOnInit is a good place to start fetching data or initializing values.
Use lifecycle hooks to keep your component's behavior clear and predictable.
Lifecycle hooks let you run code at key moments in a component's life.
They help manage resources and keep your app efficient.
Using them makes your components easier to understand and maintain.
Practice
Solution
Step 1: Understand what lifecycle hooks do
Lifecycle hooks allow you to run code at key moments like creation, update, or destruction of a component.Step 2: Identify the main benefit
This helps manage resources and keep the app efficient by running code only when needed.Final Answer:
They let you run code at specific times during a component's life. -> Option DQuick Check:
Lifecycle hooks = run code at key moments [OK]
- Thinking lifecycle hooks style components
- Believing hooks replace services
- Assuming hooks speed up loading automatically
ngOnInit lifecycle hook in an Angular component?Solution
Step 1: Recall the exact lifecycle hook name
The correct lifecycle hook method name isngOnInitwith exact casing.Step 2: Match the syntax
The method should be declared asngOnInit() { ... }inside the component class.Final Answer:
ngOnInit() { console.log('Init'); } -> Option AQuick Check:
Correct hook name and syntax = ngOnInit() { console.log('Init'); } [OK]
- Using wrong method names like onInit or init
- Incorrect casing like nginit
- Missing 'ng' prefix in method name
export class MyComponent implements OnInit {
constructor() { console.log('Constructor called'); }
ngOnInit() { console.log('ngOnInit called'); }
}Solution
Step 1: Understand Angular component creation order
The constructor runs first when the component is created, thenngOnInitruns after Angular sets input properties.Step 2: Trace the console logs
First, 'Constructor called' logs, then 'ngOnInit called' logs.Final Answer:
Constructor called\nngOnInit called -> Option AQuick Check:
Constructor runs before ngOnInit [OK]
- Thinking ngOnInit runs before constructor
- Expecting only one log message
- Confusing lifecycle order
export class SampleComponent implements OnInit {
ngOnInit() {
this.loadData();
}
loadData() {
console.log('Data loaded');
}
ngOnDestroy() {
this.loadData();
}
}Solution
Step 1: Understand purpose of ngOnDestroy
ngOnDestroy runs when the component is about to be removed. It is used to clean up resources, not to load data.Step 2: Identify misuse of loadData()
Calling loadData() during destruction is illogical because loading data is for initialization, not cleanup.Final Answer:
Calling loadData() inside ngOnDestroy is incorrect because it runs when component is destroyed. -> Option CQuick Check:
ngOnDestroy is for cleanup, not loading data [OK]
- Thinking ngOnDestroy needs a return value
- Believing lifecycle hooks can't call methods
- Assuming constructor is required with ngOnInit
Solution
Step 1: Identify hook for initial data fetch
UsengOnInitto run code once after component creation, perfect for fetching data.Step 2: Identify hook for cleanup
UsengOnDestroyto clean up resources like subscriptions before component is removed.Final Answer:
ngOnInit to fetch data, ngOnDestroy to clean up subscription -> Option BQuick Check:
Init = fetch, Destroy = cleanup [OK]
- Using constructor for async data fetch
- Confusing ngAfterViewInit with cleanup
- Using ngOnChanges for one-time fetch
Ready to prove it?
Pass the test and this pattern moves unknown
