Angular

Components & Lifecycle

Component lifecycle hooks, ngOnInit, ngOnChanges, ngOnDestroy, ngAfterViewInit, component communication, @Input, @Output

20 interview questionsยท
Junior
1

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.

2

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.

3

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.

4

Why use ngOnDestroy in a component?

5

In what order are lifecycle hooks called when creating a component?

+17 interview questions

Master Angular for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free