Change image on click using Angular2
Change image on click using Angular2
I'm trying to change the heart image of the list when I click on it but every time I click all the other heart images of the list change also.
here is a screen shoot of my list :
and here is the html list :
<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>
and the function in the component:
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";
1 Answer
1
The Image src & wasClicked property should be part of film object i.e film.imgSrc, which will update the particular row. Currently you are maintaining one property which will update all items.
<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>
Component:
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";
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
That's because they're all pointing at the same variable.
– user184994
Aug 26 at 9:37