首页 > 解决方案 > Angular document.getElementById 不能动态使用插值

问题描述

我有一个动态图像列表,我只想在用户将鼠标悬停在特定图像上时才显示不透明度。我的问题是我为每个图像动态分配了一个 id,但无法动态获取元素的属性。

我得到了 Got 插值 ({{}}) 的错误,其中表达式是预期的

<span *ngFor="let image of imagess">   
  <img  attr.id="Image{{image.id}}"
    [src]="sanitizer.bypassSecurityTrustUrl('data:'+image.mimeType+';base64, '+image.frontImage)"       
    onmouseover="style.opacity=.16;"
    onmouseout="style.opacity=1;"
    />    
  <span onmouseover="document.getElementById('Image'{{image.id}}).style.opacity=.16;"> <----Right here is what I need 

  //Icons and other things here      
  </span>    
</span>

标签: javascripthtmlcssangular

解决方案


我会将其重写为 Angular 方式:

<span *ngFor="let image of images">   
  <img
    ...
    #img   
    (mouseover)="img.style.opacity= '.16'"
    (mouseout)="img.style.opacity= '1'"
    />    
  <span 
    (mouseover)="img.style.opacity= '.16'"
    (mouseout)="img.style.opacity= '1'"
  >Hover over me</span>    
</span>

Ng 运行示例


推荐阅读