当我单击列表时,我试图更改列表的心脏图像,但是每次单击列表的所有其他心脏图像时,也会更改。
这是我的列表的屏幕截图:
这是html列表:
<ul class="list-group">
<li
class="list-group-item"
*ngFor="let film of items">
{{film.text}}
<img
[src]="imgSrc"
(click)="fav(film.text)"
class="heart">
<img
(click)="delete(film.text)"
class="deletebtn"
src="/assets/images/delete.png">
</li>
</ul>
以及组件中的功能:
imgSrc: string = "../../assets/images/heartnotclicked.png";
wasClicked = false;
fav(film) {
if (this.wasClicked === false) {
this.wasClicked = true;
this._filmService.addFavFilms(film);
this.imgSrc = "../../assets/images/heart.png";
} else {
this.wasClicked = false;
console.log(this.wasClicked);
this._filmService.deleteFav(film.text);
this.imgSrc = "../../assets/images/heartnotclicked.png";
}
}
答案 0 :(得分:2)
Image src和wasClicked属性应该是电影对象的一部分,即film.imgSrc,它将更新特定的行。当前,您正在维护一个将更新所有项目的属性。
<ul class="list-group">
<li class="list-group-item" *ngFor="let film of items" >{{film.text}}
<img [src]="film.imgSrc" (click)="fav(film)" class="heart">
<img (click)="delete(film.text)" class="deletebtn"src="/assets/images/delete.png">
</li>
</ul>
组件:
imgSrc: string = "../../assets/images/heartnotclicked.png";
wasClicked = false;
fav(film){
if(film.wasClicked === false){
film.wasClicked = true;
this._filmService.addFavFilms(film);
film.imgSrc = "../../assets/images/heart.png";
}
else {
film.wasClicked = false;
console.log(film.wasClicked);
this._filmService.deleteFav(film.text);
film.imgSrc = "../../assets/images/heartnotclicked.png";
}
}