Simon
Simon

Reputation: 2538

Angular2/Firebase - Array1 be equal to array2 without binding them together

Sorry I'm finding it difficult to word the issue I'm having correctly..

I have an array called feedCounter and an array called postFeed. I want to display the length of feedCounter and when a user clicks on it postFeed becomes equal to feedCounter, but when feedCounter gets a new element postFeed should not update with it...

What I'm doing is setting feedCounter to a snapshot in firebase:

this.subscription.on('child_added', (snapshot) => {
    this.feedCounter.push(snapshot.val());
});

and then in my html I do this:

<div (click)="postFeed = feedCounter;">{{feedCounter?.length}}</div>
<post *ngFor="let post of postFeed.reverse()"></post>

The problem is, postFeed seems to be getting binded to feedCounter after the first time I click on the div postFeed automatically gets updated, which I do not want..

How can I fix this? Thank you!

Upvotes: 0

Views: 25

Answers (2)

Tung Tran
Tung Tran

Reputation: 111

The root cause is you assign postFeed = feedCounter; so both variable will reference to the same array and add new element to feedCounter just same as add new element to postFeed. To separate those you should clone it before assign like this: postFeed = feedCounter.slice(0);

Upvotes: 1

Luan Nico
Luan Nico

Reputation: 5917

Instead of doing this in your click handler:

postFeed = feedCounter

You need to create a copy of feedcounter; otherwise, you are making them both point to the same object (the same array). So,

postFeed = copy(feedCounter)

Now the copy function you must implement, there are several ways to do it, you can google it (how to copy array javascript), use a lib like lodash, or implement it yourself.

One option is to JSON parse and unparse:

copy = (arr) => JSON.parse(JSON.stringify(arr));

You need to decide if you want shallow or deep, if you need to deal with circular dependencies, etc.

Upvotes: 1

Related Questions