In AngularJS, what is the purpose of the $onInit
function if I can do the same initialization without that function?
For example this:
module.component("myComponent", {
...
controller: function() {
const $ctrl = this;
$ctrl.$onInit = () => {
$ctrl.var1 = "hello";
$ctrl.var2 = { test: 3 };
}
}
});
Can also be done like this:
module.component("myComponent", {
...
controller: function() {
const $ctrl = this;
$ctrl.var1 = "hello";
$ctrl.var2 = { test: 3 };
}
});
Is there some case where $onInit
is necessary?
A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.
The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application.
$ctrl is the view model object in your controller. This $ctrl is a name you choose (vm is another most common name), if you check your code you can see the definition as $ctrl = this; , so basically its the this keyword of the controller function.
OnInit : ngOnInit is component's life cycle hook which runs first after constructor(default method) when the component is being initialized. So, Your constructor will be called first and Oninit will be called later after constructor method.
Per the AngularJS docs
Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element).
This gives you two guarantees:
In contrast to your first method, where neither of these facts are guaranteed (though the second one is highly probable).
In addition, as a matter of style and readability, it makes it very clear to a potential reader/reviewer that this is code that you as the developer intended to run upon initialization of this controller.
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