Search code examples
typescriptangular2-components

how to change the src of an< img> when I know the <img> id?


I display an array of images in a *ngFor loop.

itemimg.component.html

<div *ngFor="let itemimg of itemimgs" [class.selected]="itemimg === selectedItemimg" 
            (click)="onSelect(itemimg)"> 
    <img id="{{itemimg.index}}" class="thumb" src="{{itemimg.imageUrl}}" width="{{itemimg.width}}" height="{{itemimg.height}}" 
        style="float: left; margin-right: 3px; margin-bottom: 3px">
</div>

When I click on any of the images I want to replace the first image.

itemimg.components.ts (part)

  onSelect(itemimg: Itemimg): void{ 
    this.selectedItemimg = itemimg;
    var newsrc = "../../assets/images/" + itemimg.route + ".jpg";
    //alert (newsrc);
    *what-goes-here* = newsrc;    // the problem
  }

I have been googled this for over three hours but cannot find the answer. Thank you for looking.


Solution

  • Please do the following considering you always want to replace first image in the array:

    onSelect(itemimg: Itemimg): void{ 
    this.selectedItemimg = itemimg;
    var newsrc = "../../assets/images/" + itemimg.route + ".jpg";
    //alert (newsrc);
    this.itemimgs[0].imageUrl = newsrc;  
    

    }