ryasun
ryasun

Reputation: 53

Is it pointless to use $onInit in this case

I have an angularJS (1.5+) component that has some one-way binding properties that are bound to a parent controller's variables. This component uses those properties in the bindings object directly and doesn't need to set up any local variables.

When the page loads, the component's bindings are initialized and bound to default values because the parent controller initializes its variables to default values.

example code:

App.component('myComponent',{
    bindings:{
        binding_1: '<',
        binding_2: '<'
    },
    template:'<div ng-show="$ctrl.binding_1">' +
    '<input type="button" ng-click="$ctrl.clicked()">' +
    '</div>',
    controller: function () {
        var ctrl = this;

        // would ctrl.$onInit = function(){...} be beneficial here at all?

        ctrl.clicked = function(){
            console.log("ctrl.binding_2.text");
        }
});

If the component only uses its binding properties and those properties are initialized to default values via the parent controller variables upon page load, then what would be the benefit(s) of implementing $onInit and where would I expect to see this (these) benefit(s)?

Upvotes: 2

Views: 483

Answers (1)

Mike Lunn
Mike Lunn

Reputation: 2470

$onInit is the component's initialization lifecycle hook. You should perform your initialization logic there. In the case of your code sample, the component bindings would likely be accessible since they are being accessed in a click handler. Here is a small demo demonstrating $onInit.

Component Initialization with $onInit

angular.module('app',[])
.controller("MyController", function(){
  var ctrl = this;
  ctrl.title = "Hello World";
})
.component("myComponent", {
   bindings:{
        bindingOne: '<'
    },
    template: ' <h1>{{ctrl.title}}</h1>',
    controller: function(){
      this.$onInit = function(){
        this.title = this.bindingOne;
      }

    },
    controllerAs: "ctrl"
})

Component Initialization Without $onInit

  angular.module('app',[])
    .controller("MyController", function(){
      var ctrl = this;
      ctrl.title = "Hello World";
    })
    .component("myComponent", {
       bindings:{
            bindingOne: '<'
        },
        template: ' <h1>{{ctrl.title}}</h1>',
        controller: function(){
          this.title = this.bindingOne;
        },
        controllerAs: "ctrl"
    })

Upvotes: 0

Related Questions