Button that when clicked displays an image, if clicked again displays another image

Asked

Viewed 33 times

0

All right? I’m creating a button that when clicked it displays an image, and if clicked again it goes back to the old image, at the angle, currently I’m only able to catch the first action, I can’t go back to the first image.

HTML
<div (click)="clique()">
  <img src="{{ imagem }}" />
</div>
TS
imagem: string;

clique(): void {
  if(this.imagem) {
    this.imagem = 'imagem1.jpg';
  } else {
    this.imagem = 'imagem2.jpg';
  }
}

1 answer

0


Your problem there is that as you do not assign any value to the attribute image will always fall into the else because the variable is undefined, one of the ways to do what you want is to insert one more attribute that controls which of the two images will be rendered:

HTML

<div (click)="clique()">
  <img [src]="imagem" />
</div>

TS

imagem: string;
control = false;

clique(): void {
  this.control = !this.control;   // Espero que saiba o que isso faz
  if(this.control) {              // Se control igual true
    this.imagem = 'imagem1.jpg';
  } else {                        // Se control igual false
    this.imagem = 'imagem2.jpg';
  }
}

Be able to see a functional example here.

  • 1

    Thank you very much friend, it worked perfectly, and thank you for the explanation so I could realize my mistake

Browser other questions tagged

You are not signed in. Login or sign up in order to post.