所以我试图创建一个基本网站,当我点击按钮时我需要显示图像。问题是它向我显示图像,但当我点击另一个按钮向我显示另一个图像时,先前的图像保留。 这是我的代码。我使用的是Angular 4和打字稿。
component.ts
COPY failed: Forbidden path outside the build context: ../sources/
component.html
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);}
答案 0 :(得分:1)
在Angular中,您无法直接触摸DOM。
我能想到的最简单的方法:
<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"/>
在您的Typescript中,删除所有以前的代码,只需声明一个变量
imageSource: string;
答案 1 :(得分:0)
好的,这是解决方案
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 }}