0

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 ?

Edit :

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.

Community
  • 1
  • 1
Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191
  • two possible solutions. 1. change the bindings to =. 2. have a ng-if="vm.parentForm" to wrap the html and so once it is initialized, the html will re-compile. – Charlie Ng Aug 25 '17 at 17:01
  • you don't need ng-if at all to solve this : use onChanges inside your child component so every time your value will be updated the hook onChanges will be trigger inside the child component and so you can assign the new object value. ````onChanges() = function(changes) { if (changes.parentForm.currentValue !== undefined) { this.parentForm = changes.parentForm.currentValue; }```` – rbinsztock Aug 28 '17 at 10:32
  • 1
    You actually don't have to update local scope of component since it updates automatically on any binding changes. – korteee Aug 28 '17 at 13:52
  • 1
    Can you share the rest of your controller code? Perhaps the problem isn't in the binding at all. – JC Ford Aug 28 '17 at 16:28
  • 1
    make fiddle/plunk - all you have here just works – Petr Averyanov Aug 29 '17 at 11:45

1 Answers1

1

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.

aUXcoder
  • 1,048
  • 1
  • 20
  • 32