Angular Lifecycle Hooks Cheat Sheet (Enterprise Version)
1️⃣ Constructor
- When called: First, before Angular sets inputs or renders.
- Use: Only for dependency injection, not for initialization.
constructor(private api: ApiService) {
console.log('Constructor called');
}
⚠️ Don’t call API here — @Input() is not ready yet.
2️⃣ ngOnChanges
- Interface: OnChanges
- When called: Whenever @Input() changes, even before ngOnInit.
- Use: React to parent component data changes.
@Input() userId: number;
ngOnChanges(changes: SimpleChanges) {
if (changes['userId'] && !changes['userId'].firstChange) {
this.loadUserDetails(changes['userId'].currentValue);
}
}
loadUserDetails(id: number) {
this.api.get<User>(`/users/${id}`)
.subscribe(u => this.user = u);
}
3️⃣ ngOnInit
- Interface: OnInit
- When called: After first ngOnChanges.
- Use: Initialize data, forms, API calls.
ngOnInit(): void {
this.loadUsers();
this.initForm();
}
loadUsers() {
this.api.get<User[]>('/users')
.subscribe(users => this.users = users);
}
initForm() {
this.userForm = this.fb.group({
name: [''],
email: ['']
});
}
4️⃣ ngDoCheck
- Interface: DoCheck
- When called: On every change detection cycle
- Use: Custom checks not handled by Angular’s default change detection.
ngDoCheck(): void {
if (this.users.length !== this.previousLength) {
console.log('Users array changed!');
this.previousLength = this.users.length;
}
}
⚠️ Use sparingly — can impact performance.
5️⃣ ngAfterContentInit
- Interface: AfterContentInit
- When called: After <ng-content> content is projected.
- Use: Access projected child components or content.
@ContentChild('projectedTemplate') projectedTemplate!: ElementRef;
ngAfterContentInit() {
console.log('Projected content:',
this.projectedTemplate.nativeElement.textContent);
}
6️⃣ ngAfterContentChecked
- Interface: AfterContentChecked
- When called: After every check of projected content.
- Use: Detect dynamic content changes.
ngAfterContentChecked() {
console.log('Content checked!');
}
7️⃣ ngAfterViewInit
- Interface: AfterViewInit
- When called: After component view and child views initialized.
- Use: Access @ViewChild / dynamic tables / charts.
@ViewChild('userTable') table: MatTable<User>;
ngAfterViewInit(): void {
console.log('Table initialized:', this.table);
}
8️⃣ ngAfterViewChecked
- Interface: AfterViewChecked
- When called: After every change detection of component view.
- Use: Post-render actions (rare).
ngAfterViewChecked(): void {
// Example: update chart after table renders
this.updateChart();
}
9️⃣ ngOnDestroy
- Interface: OnDestroy
- When called: Just before component is destroyed.
- Use: Cleanup subscriptions, timers, DOM events.
private destroy$ = new Subject<void>();
ngOnInit() {
this.api.get<User[]>('/users')
.pipe(takeUntil(this.destroy$))
.subscribe(users => this.users = users);
this.timer = setInterval(() => console.log('Tick'), 1000);
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
clearInterval(this.timer);
console.log('Component destroyed, subscriptions cleaned!');
}
✅ Enterprise Tip: Always unsubscribe to prevent memory leaks, especially with tables, observables, and infinite scroll.
🔹 Enterprise Hook Flow Example (Dynamic Table + API)
@Component({
selector: 'app-user-table',
templateUrl: './user-table.component.html'
})
export class UserTableComponent
implements OnInit, OnDestroy, AfterViewInit {
users: User[] = [];
destroy$ = new Subject<void>();
@ViewChild(MatPaginator) paginator!: MatPaginator;
constructor(private api: ApiService) {}
ngOnInit() {
this.api.get<User[]>('/users')
.pipe(takeUntil(this.destroy$))
.subscribe(data => this.users = data);
}
ngAfterViewInit() {
// Hook paginator after view init
console.log('Paginator ready', this.paginator);
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
This covers API fetching, table integration, cleanup, and view initialization.
🔹 Quick Reference Table (Enterprise)
| Hook | Enterprise Use |
|---|---|
| Constructor | Dependency Injection only |
| ngOnChanges | React to @Input() changes |
| ngOnInit | Initialize forms, call APIs |
| ngDoCheck | Custom change detection |
| ngAfterContentInit | Projected <ng-content> access |
| ngAfterContentChecked | Check dynamic projected content |
| ngAfterViewInit | Access @ViewChild table/chart |
| ngAfterViewChecked | Post-render actions |
| ngOnDestroy | Unsubscribe & cleanup |
Comments
Post a Comment