1

I have a parent component

angular.module('app')
  .component('parentComponent', {
    template: `
          <child-component data="myData"></child-component>
    `,

I'm getting myData by asynchronous call

myMethod(params).then(data => {
    $ctrl.data = data;
});

and then I pass it down to my child component where I want modify it and display it in the template

angular.module('app')
.component('childComponent', {
    restrict: 'E',
    replace: true,
    templateUrl: '',
    bindings: {
        data: '='
    },

    controller: function () {
    const $ctrl = this;

    $ctrl.$onInit = function () {
        console.log($ctrl.data);
    }
});

Problem is that data gets passed in before it is received and because of it it is undefined in the child component.

I'm not sure how do I wait for the data before passing it down.

1
  • <child-component ng-if="data" ...> Commented Aug 6, 2018 at 15:11

1 Answer 1

2

Use the $onChanges Life-Cycle Hook

app.component('childComponent', {
    templateUrl: '',
    bindings: {
        data: '<'
    },    
    controller: function () {
        const $ctrl = this;        
        $ctrl.$onChanges = function (changes) {
            changes.data && console.log(changes.data.currentValue);
        };
    }
});

From the Docs:

Life-cycle hooks

Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the directive:

  • $onChanges(changesObj) - Called whenever one-way (<) or interpolation (@) bindings are updated. The changesObj is a hash whose keys are the names of the bound properties that have changed, and the values are an object of the form { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will also be called when your bindings are initialized.

— AngularJS Comprehensive API Reference - Life-Cycle Hooks

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.