0

I am using *ngFor to iterate through an array. The data that is displayed is something like a new feed, where a user can submit an update and it will display with username, status, a like button, and a favorite button. I am working on the feature that will add a status to 'Favorites' after the favorite button has been clicked. The issue that I am having is making sure that the status for which the favorite button is clicked, will add that specific status to the favorites. The best way I can think of doing this will be to find the index of the description of the status within the status array for that user and using that to specify which status to add.

the structure for the object looks like this:

users.feed.description

where users = User, feed = Status, description = status description

What I have been able to do is specify the user and status by:

users[0].feed[0].description

What I think needs to be done is to find the index of the selected description and return that as a value to assign to feed as:

users[0].feed[i].description

I know I need something along the lines of a for loop within my addFavorites function, but I cannot seem to get things function properly. I hope this is enough information.

My addFavorites function is currently:

addToFavorites(){
console.log('Adding to Favorites ' + this.users[0].feed[0].description);
this.favorite = this.favoritesprovider.addFavorites(this.users[0].feed[0].description);
this.toastCtrl.create({
  message: this.users[0].feed[0].description + ' has been added to your favorites!',
  duration: 3000
  }).present();
 }

It will only add the description with index of 0 (because that is what is defined). I know that my for loop should reflect something similar to

function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
    if(array[i][attr] === value) {
        return i;
    }
}
return -1;
}

which I got from How to get index of object by its property in javascript but I just cant figure out how to get things working properly.

Any help is appreciated

Logan Musselman
  • 151
  • 3
  • 14

1 Answers1

1

If you're using an *ngFor then you should have access to the current index then be able to data bind it to the div. See below

<!-- Angular -->
<div class="feed">
  <div class="feed-item" *ngFor="let feedItem of feedItems; let i = index" [attr.data-index]="i">
    {{i}} {{feedItem}}
  </div>
</div>

You can then just get the data-index attribute as i.

Riddell
  • 1,429
  • 11
  • 22