2017-04-22 83 views
-1

我想僅指定ngClass正在單擊的元素;然而,它被分配給所有其他元素。Angular2 - 僅爲當前元素指定「ngClass」

的.html

<div class="likeBtn" (click)="like()" [ngClass]="{'likeBtnClicked': clicked}" item-right>I like</div> 

.TS

like(){ 
clicked = true; 
} 
+0

被綁定到相同的「ngClass」表達的其它元件({「likeBtnClicked」:按下})? – snorkpete

+0

@snorkpete是的,正好! –

回答

0

這裏是HTML:

<div class="likeBtn" (click)="like(like1.id)" #like1 id="1" 
    [ngClass]="{'likeBtnClicked': likes[like1.id]}" item-right>I like</div> 

    <div class="likeBtn" (click)="like(like2.id)" #like2 id="2" 
     [ngClass]="{'likeBtnClicked': likes[like2.id]}" item-right>I like</div> 

`

並且這裏由具有喜歡的地圖和方法組件添加新像:

export class App { 
    likes = {}; 

    like(id) { 
    this.likes[id] = true; 
    } 
}