Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happen if i use ngOnInit method without implementing OnInit interface

Can anyone please tell me what will happen if I don't implement onInit interface and still using ngOnInit component lifecycle inside a component?

Since I used ngOnInit lifecycle hook without implementing an interface and it's worked for me the same.

So just wanted to understand why I should implement an interface?

like image 819
Anshita Singh Avatar asked May 09 '20 18:05

Anshita Singh


People also ask

Do I need to implement OnInit?

We import OnInit in order to use it, implementing OnInit is not mandatory but considered good practice): import {Component, OnInit} from '@angular/core'; We use ngOnInit to do something after the component has been created. for example you can set variables here, call methods etc.

Which interface should be implemented in a component to use ngOnInit?

Angular will automatically call this when it initializes our component but we use implement OnInt interface to add compile time checking, so when we define implement OnInit interface typescript ensures that we have a method called ngOnInit.

What is the primary reason of using ngOnInit?

One of the most common use cases for ngOnInit , is to establish observable assignments to component fields. It's good practice to do this in the ngOnInit so that observables are initialized at a predictable time in the component lifecycle.

Can I call ngOnInit manually?

userData; }); Your code within the subscribe above will AUTOMATICALLY be re-executed every time the route parameters change. So there is no need to manually call ngOnInit again.


Video Answer


1 Answers

It will still work as expected.

Interface helps us to avoid spelling and syntax mistakes.

According to recomendations from Angular Style Guide

Lifecycle interfaces prescribe typed method signatures. Use those signatures to flag spelling and syntax mistakes.

like image 113
yurzui Avatar answered Oct 07 '22 13:10

yurzui