angular 1.5 component / default value for @ binding

First of there is great documentation for components Angularjs Components`. Also what you are doing I have done before and you can make it optional by either using it or checking it in the controller itself.

For example you keep the binding there, but in your controller you have something like.

var self = this;

// self.layout will be the value set by the binding.

self.$onInit = function() {
    // here you can do a check for your self.layout and set a value if there is none
    self.layout = self.layout || 'default value'; 
}

This should do the trick. If not there are other lifecycle hooks. But I have done this with my components and even used it in $onChanges which runs before $onInit and you can actually do a check for isFirstChange() in the $onChanges function, which I am pretty sure will only run once on the load. But have not tested that myself.

There other Lifecycle hooks you can take a look at.

Edit

That is interesting, since I have used it in this way before. You could be facing some other issue. Although here is an idea. What if you set the value saved to a var in the parent controller and pass it to the component with '<' instead of '@'. This way you are passing by reference instead of value and you could set a watch on something and change the var if there is nothing set for that var making it a default.

With angularjs components '@' are not watched by the component but with '<' any changes in the parent to this component will pass down to the component and be seen because of '<'. If you were to change '@' in the parent controller your component would not see this change because it is not apart of the onChanges object, only the '<' values are.


Defining the binding vars in constructor will just initiate the vars with your desired default values and after initialization the values are update with the binding.

    //ES6
    constructor(){
      this.layout = 'column';
    }
    $onInit() {
      // nothing here
    }

To set the value if the bound value is not set ask if the value is undefined or null in $onInit().

const ctrl = this;
ctrl.$onInit = $onInit;
function $onInit() {
  if (angular.isUndefined(ctrl.layout) || ctrl.layout=== null)
    ctrl.layout = 'column';
}

This works even if the value for layout would be false.