Angular Quick Answer: Difference between constructor and ngOnInit

Daniel Kreider
Daniel Kreider - 28 May 2022

Who would-a guessed..

That...

One of the most popular Angular questions on Stack Overflow...

Is a question about the difference between Angular's constructor and the OnInit function?

Difference%20between%20Constructor%20and%20ngOnInit

Here's the quick answer.

The constructor is a Typescript feature used to instantiate the Typescript class. In most Angular projects about the only thing that should ever be done in the constructor is to inject services.

The ngOnInit function is specific to the Angular framework and is called when Angular is done creating the component. It should be called with any custom finalization like loading data for your component to display.

...

...

...

You still around?

...

...

Oh! So you want to know more.

What is the constructor?

A Typescript constructor is a simple function that is declared inside of a class.

Like this.

class CoffeeSwallower {
  name: string;

  constructor(name = "SpewCoffeeGalore") {
    this.name = name;
  }
}

It automatically gets called when we create a new instance of our class.

Since the constructor is a Typescript feature it's important to realize that there is no relationship between Angular and the constructor. Normally, you will use the constructor to define or initialize some variables. A good example of this is dependency injection as show in action below.

In this example, we use the constructor to inject Angular's HTTP client.

@Injectable()
export class HeroService {
  constructor(private httpService: HttpClient) {}

  fetchHero(id: number) {
    return this.httpService.get<Hero>('my-hero-api.com');
  }
}

What is the ngOnInit function?

The ngOnInit function is specific to Angular applications.

It is called as soon as Angular has finished initializing our component. Which allows us to finish initializing the component however we dandy-well please. For example, this is where you will call functions to load external data, etc...

Any real work should always be placed in the ngOnInit method.

According to the Angular docs, components are easier to test and debug when their constructors are simple and all real work (especially calling a remote server) is handled in a separate method.

Still doubtful about the difference?

Maybe you're still confused about the difference between the constructor and ngOnInit?

Or some of the terminology that I used?

Or maybe there's a way to explain this better?

Let me know in the comments below.

signature

Angular Consultant