Which lifecycle hooks are available in Angular

Difference between constructor and ngOnInit

The main difference between constructor and is that it is lifecycle hook and runs by constructor. Component-interpolated template and input initial values ​​are not available in the constructor, but are available in.

The practical difference is how the structure affects the code. Most initialization codes can be used after - postponed, provided this does not result in any race conditions to be created.

Constructor anti-pattern

A significant amount of initialization code makes the constructor method difficult to extend, read, and test.

A common recipe for separating the initialization logic from the class constructor is to move it to a different method such as:

can serve this purpose in components and instructions:

Addiction injection

The primary role of class constructors in Angular is dependency injection. Constructors are also used for DI annotations in TypeScript. Almost all dependencies are assigned to the class instance as properties.

An average component / instruction constructor is already large enough because it can have a multiline signature due to dependencies. This helps to insert unnecessary initialization logic into the constructor body.

Asynchronous initialization

Asynchronous initialization constructor can often be viewed as an antipattern and a smell, as class instantiation is terminated before the asynchronous routine is executed. This can lead to race conditions. If not, then and other lifecycle hooks are better places to do so, especially because they can benefit from the syntax:

If there are race conditions (including the condition that a component should not be displayed in the event of an initialization error), an asynchronous initialization routine should take place before the components are instantiated and moved to the higher-level component, router guard, etc.

Unit tests

is more flexible than a constructor and has some unit test advantages, which are discussed in detail in this answer.

Considering that unit tests are not automatically called in unit tests, methods called in can be spied on or patterned after components are instantiated.

In exceptional cases, it can be bridged completely in order to isolate other component units (e.g. some template logic).

heritage

Child classes can only extend constructors, not replace them.

Since there is no prior referencing, the initialization specifications are restricted.

Given that the Angular component or directive uses time-independent initialization logic, child classes can choose whether to invoke and when:

This cannot be implemented with the constructor alone.