Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference whether you "implements OnInit" when you use the function ngOnInit

Tags:

angular

When I use the function ngOnInit, TS lint warned me I should add implements OnInit. But I can use the function ngOnInit normally without implementing OnInit. What's the difference between the two ways?

like image 520
Eve-Sama Avatar asked Nov 27 '17 08:11

Eve-Sama


People also ask

What is ngoninit in angular?

ngOnInit is a life cycle hook called by Angular to indicate that Angular is done creating the component. We import OnInit in order to use it, implementing OnInit is not mandatory but considered good practice): We use ngOnInit to do something after the component has been created. for example you can set variables here, call methods etc.

What is the oninit method in angular?

This is the method that Angular calls when it initializes the component. OnInit is an interface that refers to the lifecycle hook. There are multiple lifecycle hooks in Angular: Each of these interfaces declares a method with the same name prefix with ng .

When should I use ngoninit?

We import OnInit in order to use it, implementing OnInit is not mandatory but considered good practice): We use ngOnInit to do something after the component has been created. for example you can set variables here, call methods etc.

What is the difference between oninit and onchanges?

Find the difference between OnInit and OnChanges. OnInit. OnInit interface is a lifecycle hook. It has a method ngOnInit(). It is called after data-bound properties of component/directive are initialized. ngOnInit() is called only once. In the lifecycle sequence, ngOnInit() is called just after first ngOnChanges() call.


2 Answers

I assume you are using Typescript

You don't have to add implements OnInit as this is TypeScript and JavaScript does not have a concept of Interfaces. So when you implement an interface, this does not actually exist at run time.

Implementing an interface gives you all the strong type checking, and the TSC will throw out any warnings.

So, I do recommend you still to use the interface for this reason, plus it's a good practice.

like image 166
Jamie Rees Avatar answered Sep 22 '22 12:09

Jamie Rees


There is no difference. It's only good style to add implements OnInit.

ngOnInit is the only method this interface requires.

https://angular.io/api/core/OnInit

like image 40
Günter Zöchbauer Avatar answered Sep 22 '22 12:09

Günter Zöchbauer