使用屬性用於存儲項目是否已加星標,並綁定到該項目以顯示其中一個或另一個圖像。然後在未加星標圖標的點擊處理程序中使用另一個函數,使請求對其進行加星標並更新屬性。
<img *ngIf="!isStarred" src="./images/star_unfilled.png" id="star-result" (click)="star()" alt="Star this result">
<img *ngIf="isStarred" src="./images/star_filled.png" id="star-result" (click)="unstar()" alt="Unstar this result">
並在視圖模型,你有這樣的:
isStarred: boolean = false;
star() {
// Do whatever it takes to star something
// And at the end update local status
isStarred = true;
}
unstar() {
// Do whatever it takes to star something
// And at the end update local status
isStarred = false;
}
你可以選擇性地還使用單個img
元素並綁定取決於isStarred
值src屬性。而不是star()和unstar()方法使用單一的toggleStar()
方法。數十個選項在這裏。