Components & Lifecycle
Component lifecycle hooks, ngOnInit, ngOnChanges, ngOnDestroy, ngAfterViewInit, component communication, @Input, @Output
1What is a lifecycle hook in Angular?
What is a lifecycle hook in Angular?
Answer
A lifecycle hook is a special method automatically called by Angular at key moments in a component or directive's lifecycle. These hooks allow executing code at specific stages like creation, updates or destruction. The most common hooks are ngOnInit, ngOnChanges and ngOnDestroy.
2When is ngOnInit called?
When is ngOnInit called?
Answer
ngOnInit is called once after the first ngOnChanges, once all @Input properties have been initialized. This is the ideal hook to initialize component data, start subscriptions or call services. It is preferable to constructor for initialization logic since all bindings are guaranteed available.
3What is the main difference between ngOnChanges and ngOnInit?
What is the main difference between ngOnChanges and ngOnInit?
Answer
ngOnChanges is called every time an @Input property value changes and receives a SimpleChanges object containing old and new values. ngOnInit is called only once after first initialization. Use ngOnChanges to react to input changes and implement logic dependent on @Input values. Prefer ngOnInit for one-time initialization like API calls or initial configuration.
Why use ngOnDestroy in a component?
In what order are lifecycle hooks called when creating a component?
+17 interview questions
Other Angular interview topics
TypeScript Basics
TypeScript Advanced
Angular Fundamentals
Services & Dependency Injection
Angular Modules Organization
Angular CLI
Directives & Pipes
Routing & Navigation
Reactive Forms
Template-driven Forms
RxJS Fundamentals
RxJS Operators
HttpClient & API Calls
Basic State Management
Change Detection
Angular Signals
Standalone Components
Angular Unit Testing
End-to-End Testing
Build & Optimization
NgRx Fundamentals
NgRx Advanced
Angular Architecture
Performance Optimization
Security & Best Practices
Advanced RxJS Patterns
Angular Universal & SSR
Angular Micro-frontends
Master Angular for your next interview
Access all questions, flashcards, technical tests, code review exercises and interview simulators.
Start for free