Questions
What is the component lifecycle and how do you use it in Angular?
The Scenario
You are a frontend engineer at a social media company. You are building a new component that needs to fetch data from an API when it is created.
You are not sure where to put the data fetching logic in the component’s lifecycle.
The Challenge
Explain what the component lifecycle is in Angular and what the different lifecycle hooks are. Which lifecycle hook would you use to fetch data from an API, and why?
A junior engineer might not be aware of the component lifecycle. They might try to fetch the data in the constructor, which would work, but it would not be the most optimal solution.
A senior engineer would be able to provide a detailed explanation of the component lifecycle and the different lifecycle hooks. They would also be able to explain the trade-offs between each hook and would have a clear recommendation for which one to use for fetching data.
Step 1: Understand the Component Lifecycle
The component lifecycle is a series of stages that a component goes through, from when it is created to when it is destroyed.
Step 2: The Different Lifecycle Hooks
| Hook | Description |
|---|---|
ngOnChanges() | Called before ngOnInit() and whenever one or more data-bound input properties change. |
ngOnInit() | Called once, after the first ngOnChanges(). |
ngDoCheck() | Called during every change detection run. |
ngAfterContentInit() | Called after content (ng-content) has been projected into view. |
ngAfterContentChecked() | Called after the projected content has been checked. |
ngAfterViewInit() | Called after the component’s view (and child views) has been initialized. |
ngAfterViewChecked() | Called after the component’s view (and child views) has been checked. |
ngOnDestroy() | Called just before the component is destroyed. |
Step 3: Choose the Right Tool for the Job
For our use case, we should use the ngOnInit() hook to fetch the data from the API. This is because we want to make sure that the component has been initialized before we try to fetch the data.
Step 4: Code Examples
Here’s how we can use the ngOnInit() hook to fetch data from an API:
import { Component, OnInit } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'my-component',
template: '<h1>{{ myData }}</h1>'
})
export class MyComponent implements OnInit {
myData: string;
constructor(private myService: MyService) {}
ngOnInit() {
this.myService.get_data().subscribe(data => {
this.myData = data;
});
}
} Practice Question
You want to perform an action just before a component is destroyed, such as cleaning up a timer. Which lifecycle hook would you use?