What are Angular Lifecycle Hooks?
Angular components and directives go through lifecycle phases:
- Creation → Angular sets up the component.
- Rendering → Angular renders templates & bindings.
- Update → Angular detects changes.
- Destruction → Angular cleans up component.
Lifecycle hooks are special interface methods you can implement to run code at these stages.
2️⃣ Main Lifecycle Hooks in Angular
| Hook | Interface | Called When | Example Use Case |
|---|---|---|---|
| ngOnChanges | OnChanges | Input-bound properties change | React to @Input() updates |
| ngOnInit | OnInit | Component initialized (after first ngOnChanges) | Fetch initial data from API |
| ngDoCheck | DoCheck | Every change detection cycle | Custom change detection logic |
| ngAfterContentInit | AfterContentInit | Projected content initialized (<ng-content>) | Access content children after projection |
| ngAfterContentChecked | AfterContentChecked | After every check of projected content | Detect content changes dynamically |
| ngAfterViewInit | AfterViewInit | Component’s view initialized | Access @ViewChild elements |
| ngAfterViewChecked | AfterViewChecked | After each check of component’s view | Run post-render updates |
| ngOnDestroy | OnDestroy | Component about to be destroyed | Cleanup subscriptions, timers |
3️⃣ Basic Example
import { Component, Input, OnInit, OnChanges, OnDestroy, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-lifecycle-demo',
template: `<h3>{{ name }}</h3>`
})
export class LifecycleDemoComponent implements OnInit, OnChanges, OnDestroy {
@Input() name: string = '';
constructor() {
console.log('Constructor called');
}
ngOnChanges(changes: SimpleChanges) {
console.log('ngOnChanges', changes);
}
ngOnInit() {
console.log('ngOnInit: component initialized');
}
ngOnDestroy() {
console.log('ngOnDestroy: component destroyed');
}
}
4️⃣ Hooks in Directives
import { Directive, ElementRef, OnInit, OnDestroy } from '@angular/core';
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective implements OnInit, OnDestroy {
constructor(private el: ElementRef) {}
ngOnInit() {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
ngOnDestroy() {
this.el.nativeElement.style.backgroundColor = '';
}
}
5️⃣ Practical Enterprise Use Cases
-
ngOnInit
- Call API once when component loads.
- Initialize forms (FormGroup).
-
ngOnChanges
- Update component when @Input() changes.
- React to parent data dynamically.
-
ngAfterViewInit
- Access @ViewChild table or chart and apply dynamic logic.
-
ngOnDestroy
- Unsubscribe from observables (takeUntil, Subscription.unsubscribe()).
- Remove timers or DOM event listeners.
-
ngDoCheck
- Run custom change detection for non-bound properties.
6️⃣ Quick Tips
- Use ngOnInit instead of constructor for most initialization.
- Always unsubscribe in ngOnDestroy to avoid memory leaks (very important for enterprise apps).
Comments
Post a Comment