首页 > 解决方案 > 单击时如何更改文本和按钮图像(或按钮)

问题描述

我正在使用角度。当我单击一个按钮时,我会得到一个带有一些选项的下拉列表。单击时如何更改按钮图像或按钮和文本?目标是让它在再次单击时返回其原始状态。

我将图像留在这里以便更好地理解。

在我的例子中,按钮将是一个图像。

图片

我想要的是:我单击按钮并打开下拉列表,在该下拉列表中,当我单击开始时,我希望更改按钮的图像(或按钮)并开始暂停。如果您再次执行相同操作,则会发生相反的情况……也就是说,如果您有暂停,按下它会更改按钮,暂停变为开始。

有可能的?谁能帮我?

例如,我的代码

密码笔

HTML

  <div class="dropdown">
    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
     <img src="">
    </button>
    <div class="dropdown-menu">
      <a class="dropdown-item">Start</a>
      <a class="dropdown-item">Add new</a>
    </div>
  </div>

我正在使用 Angular,如果有人可以帮助我使用他们的资源获得解决方案,我真的很感激

标签: htmlcssangular

解决方案


使用变量来存储当前状态并使用它的值切换视图。

app.component.ts

currentState : string = 'pause'

app.component.html

<div class="dropdown">
    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
        <!-- Image is to be shown by default -->
        <img src="1.png" *ngIf="currentState=='pause'"">
        <!-- Image is to be shown on clicking start -->
        <img src="2.png" *ngIf="currentState=='start'"">
    </button>
    <div class="dropdown-menu">
        <a class="dropdown-item" *ngIf="currentState=='pause'" (click)="currentState='start'">Start</a>
        <a class="dropdown-item" *ngIf="currentState=='start'" (click)="currentState='pause'">Pause</a>
    </div>
</div>

推荐阅读