Lucie Schaffner
Lucie Schaffner

Reputation: 35

how to display an image from a button angular 4

So I'm trying to make a basic website and I need to display an image when I click on a button. The problem is that it displays me the image but when I click on another button to diplay me an another image the precedent image stays. here is my code. I'm using Angular 4 and typescript.

component.ts

openPredictionImg() {
const myImg = new Image();
myImg.useMap = '../../assets/prediction.png';
const img = document.createElement('img');
document.body.appendChild(img);
img.setAttribute('src', myImg.useMap);
img.onload = (stop);}

openRebalancingImg() {
const myImg = new Image();
myImg.useMap = '../../assets/rebalancing.png';
const img = document.createElement('img');
document.body.appendChild(img);
img.setAttribute('src', myImg.useMap);
img.onload = (stop);}

openVisualizationImg() {
const myImg = new Image();
myImg.useMap = '../../assets/visualization.png';
const img = document.createElement('img');
document.body.appendChild(img);
img.setAttribute('src', myImg.useMap);
img.onload = (stop);}

component.html

<button class="predictionBtn "(click)="openPredictionImg()" style="width: 10%">Prediction</button>

<button class="rebalancingBtn" (click)="openRebalancingImg()" style="width: 10%">Rebalancing</button>

<button class="visualizationBtn" (click)="openVisualizationImg()" style="width: 10%">Visualization</button>

Upvotes: 0

Views: 9681

Answers (2)

Lucie Schaffner
Lucie Schaffner

Reputation: 35

Ok here is the solution

component.ts

text = '';
openPrediction() {
this.text = '...' }

component.html

<button class="predictionBtn " (click)="imageSource = '../../assets/prediction.png'; openPrediction()" >Prediction</button>
<img [src]="imageSource" *ngIf="imageSource" style="width: 10%"/>
{{ text }}

Upvotes: 0

user4676340
user4676340

Reputation:

In Angular, you don't touch the DOM directly.

The simplest way I can think of :

<button class="predictionBtn "(click)="imageSource = '../../assets/prediction.png'" style="width: 10%">Prediction</button>

<button class="rebalancingBtn" (click)="imageSource = '../../assets/rebalancing.png'" style="width: 10%">Rebalancing</button>

<button class="visualizationBtn" (click)="imageSource = '../../assets/visualization.png'" style="width: 10%">Visualization</button>

<img [src]="imageSource" *ngIf="imageSource"/>

In your Typescript, remove all of your previous code and simply declare a variable

imageSource: string;

Upvotes: 1

Related Questions