Loading

Quipoin Menu

Learn • Practice • Grow

angular / Component Lifecycle
interview

Q1. What is the component lifecycle in Angular?
Angular components have a lifecycle managed by Angular. It starts when the component is created and ends when it''s destroyed. Angular provides lifecycle hooks to tap into key events: creation, input changes, change detection, and destruction. These hooks allow you to perform actions at specific moments.

Q2. What are the Angular lifecycle hooks?
Common hooks (in order): ngOnChanges (called when input properties change), ngOnInit (once after first ngOnChanges), ngDoCheck (during every change detection), ngAfterContentInit (after content projection), ngAfterContentChecked, ngAfterViewInit (after view initialization), ngAfterViewChecked, ngOnDestroy (before destruction). Implement the interfaces to use them.

Q3. What is the purpose of ngOnInit?
ngOnInit is called once after the first ngOnChanges. It''s used for component initialization logic, such as fetching data, setting up subscriptions, or initializing properties that depend on input values. It''s a better place than the constructor for such tasks because input properties are set.

Q4. What is the difference between constructor and ngOnInit?
The constructor is a TypeScript feature, called when the class is instantiated. It''s used for dependency injection and simple initialization. ngOnInit is an Angular lifecycle hook called after the component''s inputs are set. Angular-specific initialization should go in ngOnInit, not the constructor.

Q5. When would you use ngOnDestroy?
ngOnDestroy is called just before the component is destroyed. It''s used for cleanup: unsubscribing from observables, detaching event handlers, stopping timers, or releasing resources. This prevents memory leaks. It''s important to implement this hook when you have manual subscriptions.