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 :



enter image description here



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






That's because they're all pointing at the same variable.
– user184994
Aug 26 at 9:37




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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế