【问题标题】:how to display an image from a button angular 4如何从按钮角度显示图像4
【发布时间】:2018-03-16 10:09:27
【问题描述】:

所以我正在尝试制作一个基本网站,并且在单击按钮时需要显示图像。问题是它向我显示了图像,但是当我单击另一个按钮向我显示另一个图像时,先前的图像仍然存在。 这是我的代码。我正在使用 Angular 4 和打字稿。

组件.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>

【问题讨论】:

    标签: html angular typescript


    【解决方案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;
    

    【讨论】:

    • 非常感谢我还有一个问题
    • 如何向按钮添加文本和图像
    • 我已经尝试过你的代码,但它没有显示我的图像
    • 按钮只是一个标签,就像你将它添加到一个div中一样。
    • 您的问题中没有文字。
    【解决方案2】:

    好的,这就是解决方案

    组件.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 }}
    

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 1970-01-01
      • 2019-05-09
      • 2021-08-22
      • 1970-01-01
      • 2022-01-26
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多