【问题标题】:Change button value Angular 7 [closed]更改按钮值Angular 7 [关闭]
【发布时间】:2019-06-25 11:00:18
【问题描述】:

一个问题:

<button (click)="activateMotion(1)">
    <img class="emotion-icon" id="positive-icon" src="" />
</button>
<button (click)="activateMotion(-1)">
    <img class="emotion-icon" id="negative-icon" src="" />
</button>

我有两个按钮,其值为图像。我想写一个函数调用:activateMotion()。我想根据值 1 或 -1 更改按钮内的图像。我可以使用 jQuery 来实现这里的目标,但我正在用 Angular 编写应用程序。

【问题讨论】:

    标签: javascript jquery angular angular6 angular7


    【解决方案1】:

    你的问题太宽泛了,因为你显然还没有尝试过任何东西,但它看起来像这样:

    <button [innerHTML]="myComponentVariableName"></button>
    

    然后,在您的函数中,您将有条件地渲染图像:

    let myComponentVariableName = '';
    
    if (something) {
        myComponentVariableName = '<img ... />';
    } else {
        myComponentVariableName = '<img ... />';
    }
    

    您也可以将图像放入标记中,然后更改源属性。

    <button><img [src]="myComponentVariableName" /></button>
    

    【讨论】:

      【解决方案2】:

      您也可以为您的图像元素添加一个模板引用,并将其传递给您的函数调用,然后设置src 属性:

      <button (click)="activateMotion(1, img1)">
          <img #img1 class="emotion-icon" id="positive-icon" src="" />
      </button>
      <button (click)="activateMotion(-1, img2)">
          <img #img2 class="emotion-icon" id="negative-icon" src="" />
      </button>
      
      const src1 = '...';
      const src2 = '...';
      
      activateMotion(value: number, img: HTMLElement): void {
          if (value === 1) {
              img.setAttribute('src', src1);
          } else {
              img.setAttribute('src', src2)
          }
      }
      

      或者更简单,您可以通过图像上的输入绑定来更改 src:

      <img [src]="..." />
      

      【讨论】:

      • 为什么不将引用图像的模板引用变量传递给函数?此外,该变量将引用 HTMLElement(或更具体的类型),而不是 ElementRef,这与将此类变量与 ViewChild 一起使用时不同。
      • 嗯,你说得对,我会修改我的答案
      猜你喜欢
      • 1970-01-01
      • 2014-08-23
      • 2021-04-24
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多