zodiac645
zodiac645

Reputation: 191

Update a value of object value inside *ngFor

I have this array of objects which holds bunch of comments:

  comments: Comment[];

And this array is filled up inside ngOnInit() function by invoking service code. Later on, there is a key in my comments array which is commentPlus among with other keys. This value represents the total upvotes for a comment. I use its value inside my html like this:

<div class="media mb-3" *ngFor="let comment of comments; trackBy: trackByFn">...
<a class="btn btn-success" (click)="upVote()" [ngClass]="{'active' : comment.voted > 0 }"><i class="fa fa-thumbs-up"></i> {{comment.commentPlus}}</a>

What I want is to update the value {{comment.commentPlus}} and style of the button whenever user hits the button. Below is the code for upVote() function

upVote(commentId: number, userId: number){
    userId = this.userId;
    commentId = 4;    //I just assigned some number that I know it exists in my database for testing.
    this.service.upVote(commentId, userId).subscribe();
}

But the problem is that neither style change that should be performed by [ngClass]="{'active' : comment.voted > 0 }" nor new value for {{comment.commentPlus}} reflects in front end. Backend is working as it should be, but these two changes require page to be refreshed.

export class Yorum {
  commentId?: number;
  userId?: number;
  comment?: string;
  commentPlus?: number;
  commentMinus?: number;
  voted?: number;
}

Upvotes: 1

Views: 783

Answers (2)

Tahmasb
Tahmasb

Reputation: 59

well you should update you'r model after server response

change you'r html to

<div class="media mb-3" *ngFor="let comment of comments; trackBy: trackByFn">...
<a class="btn btn-success" (click)="upVote(comment)" [ngClass]="{'active' : comment.voted > 0 
}"><i class="fa fa-thumbs-up"></i> {{comment.commentPlus}}</a>

then

upVote(comment){
    userId = this.userId;
    commentId = 4;    //I suggest =====> commentId = comment.id
    this.service.upVote(commentId, userId).subscribe(
      data=>{
         if(data){ //it depend's on you'r server response :)
           comment.voted = 1 ; //for example 
           comment.commentPlus = 1 ; 
         }
      },
      error=>{
        console.log(error);
      }
    );
}

and it's done.

Upvotes: 1

Jatinder Pal Singh
Jatinder Pal Singh

Reputation: 236

I don't see where your comments array is being updated.

You could do 2 things:

  1. Update your comments array with new values for the comment that you just updated, inside this.service.upVote subscribe's success callback.

  2. Have an Rxjs Subject inside your service. Subscribe to this Subject inside your component's OnInit and inside it's success callback update your comments array. Broadcast new value on this Subject from inside this.service.upVote subscribe's success callback.

Upvotes: 0

Related Questions