Reputation: 239
I want make a feature that users can like comments similar instagram can like others posts.
<div *ngFor="let comment of comments | orderBy: '-'+orderBy">
<div class="comment-item" >
<div class="row">
<div class="col-md-8">
{{comment.userName}}
</div>
<div class="col-md-4">
{{comment.time | timeAgo}}
<i class="fa fa-heart-o" aria-hidden="true" (click)="likeComment(comment._id)"
[@notliked]="notliked"></i>
<i class="fa fa-heart" aria-hidden="true" (click)="unlikeComment(comment._id)"
[@liked]="liked"></i>
{{comment.like}}
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="comment-content">{{comment.textArea}}</p>
</div>
</div>
</div>
then I create two variable in component to control which icon should display.
notliked = 'open';
liked = 'close';
likeComment(commentId) {
this.liked = 'open';
this.notliked = 'close';
this.dataService.likeComment(commentId).subscribe(
res=>{
},
error => console.log(error)
)
}
unlikeComment(commentId) {
this.liked = 'close';
this.notliked = 'open';
this.dataService.unlikeComment(commentId).subscribe(
res=>{
},
error => console.log(error)
)
}
My problem is all my loop items by *ngFor changed in same time, and I hope just change selected one. I know I can't use global variable, but how to bind a property on elements separately created in *ngFor? thanks!
Upvotes: 1
Views: 614
Reputation: 4204
you have to add one more key 'is_liked' into your array 'comments'. due to which we identify whether the comment is liked or disliked.
comments=[ {is_liked:false} ]
in your method pass the index of the array and make that comment liked or disliked accordingly
likeComment(commentId,index) {
comment[index].is_liked=true;
this.liked = 'open';
this.notliked = 'close';
this.dataService.likeComment(commentId).subscribe(
res=>{
},
error => console.log(error)
)
}
to add key in your array object, run the loop like this
for(let i=0;i<comments.length;i++){
comments[i].is_liked=false;
}
Upvotes: 1
Reputation: 86740
Try like this without using any global variable, may help you
<i class="fa fa-heart-o" aria-hidden="true" (click)="likeComment(comment)"
[@notliked]="comment?.liked"></i>
<i class="fa fa-heart" aria-hidden="true" (click)="unlikeComment(comment)"
[@liked]="!comment?.liked"></i>
likeComment(commentId) {
commentId.liked = true;
}
unlikeComment(commentId) {
commentId.liked = false;
}
Upvotes: 1