Angular Quick Answer: Difference between constructor and ngOnInit


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?

Should you use ngOnInit or the constructor in Angular to initialize the component?

What is ngOnInit in Angular used for?

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

So what is the constructor in Angular used for?

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. Like this.

const myVar = new CoffeeSwallower("HelloWorld")

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 components.

It is called as soon as the Angular framework has finished initializing a 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?

Don't hesitate to reach out and let me know.

signature

Angular Developer