Reputation: 11
I am trying to change an image using Angular when a button is clicked. I already have the function change text on the page, but am failing to figure out how to change an image. Each function would have a different image associated with it. I have tried a few variations of this.imgsrc in function but none seem to work. Edit: I am trying to have a message and an image displayed in two different spots when the button is clicked. The message from the code below is displayed at the top and the image I would like displayed would be on the right.
<div>{{clickMessage}}</div>
<button (click)="onclick1()" class="button">1</button>
<button (click)="onclick2()" class="button">2</button>
<button (click)="onclick3()" class="button">3</button>
<button (click)="onclick4()" class="button">4</button>
<button (click)="onclick5()"class="button">5</button>
Component code
export class ChangeStratComponent implements OnInit {
clickMessage = '';
constructor() { }
ngOnInit() {
}
onclick1() {
this.clickMessage = 'click 1';
}
onclick2(){
this.clickMessage = 'Click 2';
}
onclick3() {
this.clickMessage = 'Click 3';
}
onclick4() {
this.clickMessage = 'Click 4';
}
onclick5() {
this.clickMessage = 'Click 5';
}
}
Upvotes: 1
Views: 11269
Reputation: 31
This should help https://stackblitz.com/edit/angular-scm9cy. I refactored a little bit repeatable code using "*ngFor". Component:
export class ChangeStratComponent {
imageSrc = '';
messageText = '';
imageButtons = [
{
src: 'photo-src',
name: 'image-1'
},
{
src: 'photo-src',
name: 'image-2'
},
{
src: 'photo-src',
name: 'image-3'
}
]
constructor() {
}
onClick(imageNameObject) {
this.imageSrc = imageNameObject.src;
this.messageText = imageNameObject.name;
}
}
HTML:
<img src="{{imageSrc}}">
<div>{{messageText}}</div>
<button *ngFor="let imageButton of imageButtons; let i = index"
(click)="onClick(imageButton)" class="button">{{i}}</button>
Upvotes: 3