2017-03-06 42 views
1

我想做一個功能,用戶可以喜歡評論類似instagram可以像其他職位一樣。元素在* ngFor

<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> 

然後創建在組分來控制哪些圖標應該顯示兩個可變。

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) 
    ) 
} 

我的問題是* ngFor的所有循環項目在同一時間改變,我希望只是改變選定的一個。我知道我不能使用全局變量,但如何綁定在* ngFor中單獨創建的元素的屬性?謝謝!

+0

你在用'comment._id'傳遞給'likeComment(...)''''和'similarComment(...)''嗎? –

+0

對不起,我錯過了一些東西,然後再次編輯。我發表comment._id服務器然後功能好吧:) – PaulHuang

回答

1

嘗試這樣不使用任何全局變量,可以幫助你

<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; 
} 
+0

對不起,我不知道'[@XYZ]'但語法將與我張貼相同 –

+1

非常感謝! [@XYZ]是我用過的動畫,所以它應該被刪除。我希望一次顯示一個圖標,爲了做到這一點,我認爲我必須添加* ngIf。不幸的是,我使用你的代碼仍然得到錯誤: 無法在字符串'58bcc8238ba8230f6cb8f5c2' 上創建'喜歡'屬性,但我相信它幾乎成功。 – PaulHuang

+0

非常感謝您提供與動畫相關的信息。 –

1

你必須添加一個更重要的「is_liked」到你的陣列「評論」。由此我們確定評論是喜歡還是不喜歡。

註釋= [ {is_liked:假} ]

在方法

傳遞數組的索引,並使該評論喜歡或相應地不喜歡

likeComment(commentId,index) { 
    comment[index].is_liked=true; 
    this.liked = 'open'; 
    this.notliked = 'close'; 
    this.dataService.likeComment(commentId).subscribe(
     res=>{ 

     }, 
     error => console.log(error) 
    ) 
} 

在你的陣列對象添加鍵,像這樣運行循環

for(let i=0;i<comments.length;i++){ 
    comments[i].is_liked=false; 
} 
+0

我認爲它會工作,但如何在comments數組中分配comment = [{is_liked:false}],謝謝。 – PaulHuang

+0

我編輯了我的答案。看那個 – Mubashir