Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular TS Lint onInit vs ngOnInit

Tags:

angular

tslint

I received a warning from TS Lint that I need to implement OnInit interface and provided me with a link to this page : https://angular.io/docs/ts/latest/guide/style-guide.html#!#09-01

What is the difference between onInit and ngOnInit. Both worked for me . Why is ok to use ngOnInit and not onInit which is much simple to write?

like image 658
Doua Beri Avatar asked Oct 28 '25 04:10

Doua Beri


1 Answers

Angular always checks for lifecycle hooks, whether your class implements the interface or not.

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

So if you have this class:

export class MyComponent {
    ngOnInit() { ... }
}

It will work fine (ngOnInit will be called by the framework). However, it is a good idea to implement the interface to ensure the method has been properly implemented.

export class MyComponent implements OnInit {
    ngOnInit() { ... }
}

Note that onInit is NOT a lifecycle hook and will not be called by Angular -- it is simply the name of the interface saying that you implement ngOnInit method somewhere in your class.

like image 177
chrispy Avatar answered Oct 29 '25 22:10

chrispy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!