I my component I'm passing an object as a binding,
.component('selectionButton', {
bindings: {
parentForm : '<'
},
templateUrl: 'selection-button-component.html',
controller: 'selectionButtonController',
controllerAs: 'selBtnCtrl'
});
The problem is that the object I'm passing is not loaded yet when my component is initialized, so in the $onChanges hook I did this :
vm.$onChanges = function(newObj){
if(angular.isDefined(newObj.parentForm.currentValue)){
vm.parentForm = newObj.parentForm.currentValue;
}
};
In my controller I call vm.parentForm
in a function, which I trigger when I click on a button after my page is fully loaded, but I always get it as undefined
, even when I changed it's value using $onChanges
.
When I inspected the vm.$onChanges
function I can see that the value of vm.parentForm
is getting the new value in changesObj.parentForm
.
How can I solve this ?
I tried to wrap my element with an ng-if
as following:
<span ng-if="fullPage.posteForm">
<selection-button parent-form="fullPage.posteForm" ></selection-button>
</span>
but this didn't work. I also tried two-way binding which didn't work as well.
When you pass an object to a component it might not be ready because you are waiting for a promise or another action to be resolved but the object definition is there as undefined. For that kind of escenario you can use isFirstChange()
.
Here is a working example that illustrate such case JSFiddle example. Open your console to see when your bindings get updated after the timeout.
Note: if the object name used in the component's template is equal to the one passed to the component you don't need to create a new object, it will be updated in your component and available in the template.