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?
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.
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 .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With