2

I am using legacy angularjs 1.5 with typescript. The data is not getting updated in Active User Card when it changes in parent

Parent

<active-user-card active-users="response.activeUsers"></active-user-card>

Active User Card

export class ActiveUserCard {
  activeUsers: number;
  data: Array<IChartData>;

  constructor() {

    ........
    ........
    this.inactiveUsers = (totalUsers - this.activeUsers) || 0;

    this.data = [
      {name: "Active users",   y: this.activeUsers},
      {name: "Inactive users", y: this.inactiveUsers}
    ];
    ........
    ........
  }
}

angular.module('tm')
  .directive('activeUserCard', [function() {
    return {
      restrict: 'E',
      scope: {
        activeUsers: '<'
      },
      bindToController: true,
      controller: ActiveUserCard,
      controllerAs: 'auc',
      templateUrl: "./active-user-card.html"
    };
  }]);

2 Answers 2

1

Well, the one place you're updating data is the component's constructor (so, run once). Use the $onChanges hook.

https://docs.angularjs.org/guide/component

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

Comments

0

First of all parent data if being used in directly in HTML then it gets reflected immediately using Angular's $watch.

But here you would want change to be reflected in this.data variable of your component. That you have to listen to changes and then update this.data.

$onChanges(changes) {
    if (changes.activeUsers&& changes.activeUsers.currentValue) {
      // update your code here
      // i don't know where totalusers are comigng in below but you just figure out.
       const inactiveUsers = (totalUsers - changes.activeUsers.currentValue) || 0;

       this.data = [
          {name: "Active users",   y: changes.activeUsers.currentValue},
          {name: "Inactive users", y: inactiveUsers}
      ];
    }
  }

I would recommend try to re-use code. take out code from constructor and make method to set data which takes total users and active users as args and make data. Same method should get called from $onChanges hooks with changes.activeUsers.currentValue. So code will be clean

Thanks

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.