-1

I have a service that holds two arrays:

activeUsers: { name: string; id: number }[] = [
    { name: "Jimmy", id: 0 },
    { name: "Jaden", id: 1 },
  ];
inactiveUsers: { name: string; id: number }[] = [
    { name: "Heiji", id: 2 },
    { name: "Pheonix", id: 3 },
    { name: "Miles", id: 4 },
  ];

And at various points in time, I will change these arrays using a push method.

this.removeUser(data.id);
if (data.status === "active") {
  this.activeUsers.push({ name: data.name, id: data.id });
} else {
  this.inactiveUsers.push({ name: data.name, id: data.id });
}

I then receive them in two separate components:

ngOnInit() {
    this.users = this.usersService.activeUsers;
  }

They then render the data to the screen:

<li class="list-group-item" *ngFor="let user of users">
    {{ user.name }} |
    <a href="#" (click)="onSetToInactive(user.id)">Set to Inactive</a>
</li>

Now, what I would expect to happen is that when I change the arrays using push, the data on the screen should change. But instead what's happening is that the original data stays, but the output never changes. I've even used console logs to make sure the arrays are actually changing, and they are-- fairly consistently too, but it never 'reaches' the dom. I've found two 'solutions' but neither make sense as to 'why' I would need them, and since i'm learning angular, i'm trying to understand why it's happening. The first fix is that I can change the code in the components to:

ngOnInit() {
    setInterval(() => {
      this.users = this.usersService.inactiveUsers;
    }, 100);
  }

or I can remove removeUser() call. Leaving this block of code in the service:

if (data.status === "active") {
      this.activeUsers.push({ name: data.name, id: data.id });
    } else {
      this.inactiveUsers.push({ name: data.name, id: data.id });
    }

Now, it seems to be a time issue. Either I can wait before setting the data in the component, or I can set the data faster. The removeUser() method is admittedly slow-- but I don't understand why it doesn't simply re-render the component if the data has changed?

Andre Thompson
  • 300
  • 2
  • 9
  • This issue is addressed many times in the forums, check this with a good answer: https://stackoverflow.com/questions/43223582/why-angular-2-ngonchanges-not-responding-to-input-array-push – Dani P. Feb 12 '21 at 22:46

1 Answers1

-2

Solved: It turns out my method was reassigning the array, so I had to change to a new method that only mutated it.

Andre Thompson
  • 300
  • 2
  • 9