Skip to main content

Angular: Constructor vs ngOnInit , Basic differences

 Angular: Constructor vs  ngOnInit, Basic differences

 

Constructor is the feature provided by ES6 (i.e. Typescript)

ngOnInit is provided by Angular itself

     

interface OnInit {

  ngOnInit(): void

}

 

Before seeing what was the order of execution let’s see if both is not available what will happen,

 

You can see that the Angular s happily compiling and executing the code even the constructor or ngInit is not present

 


 


   

 

As a next step we are trying to implement the ngOnInit interface explicitly, let’s see what will happen

 


 

 

We are getting the following error

 

Class 'AppComponent' incorrectly implements interface 'OnInit'.
Property 'ngOnInit' is missing in type 'AppComponent' but required in type 'OnInit'.

 

So we need to implement the ngOnInit if we are specifying in the class

 

After implementing the ngOnInit we are getting the page back to normal

 


 

So what is the order of execution now.

 

To find this we will create a constructor and provide the

 

console.log

 

 


 

In the output we will see the constructor is loading first and then the ngOnInit

 

 

Example available at

https://stackblitz.com/edit/angular-ivy-avjhdh

 

 

 

 

 


Comments

Popular posts from this blog

Task Parallel Library (TPL) and Akka.NET: Differences

Task Parallel Library (TPL) and Akka.NET are both powerful tools in the .NET ecosystem for handling parallelism and concurrency, but they serve different purposes and use different models of computation. Here are some key differences:s 1.    Actor Model vs Task-Based Model: Akka.NET is built around the actor model, where actors are the fundamental units of computation and they communicate by exchanging messages. TPL, on the other hand, is task-based. It's designed to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. TPL uses tasks (which are independently executing work units) and provides various ways to control and coordinate them. 2.    Fault Tolerance: One of the key features of Akka.NET is its built-in fault tolerance. It has a "let-it-crash" philosophy, where the system is designed to self-heal from errors. If an actor fails, its parent actor can decide on the supervision strategy: either to resta

Extension Methods - Advanced

Here we will see how can we use the Extension Methods in advanced manner in other types Imagine you often need to retrieve items from a List based on a custom criterion that the built-in LINQ methods don't cover. Extension Methods for Lists: Filtering based on Custom Criteria And the output would be   Extending Enums: Displaying Descriptive Strings Output: Extending DateTime: Calculating Age     Output: The code samples can be found at https://github.com/oneananda/C_Sharp_Examples/tree/main/ExtensionMethods