代码之家  ›  专栏  ›  技术社区  ›  Ibrahim Azhar Armar

在ngFor中切换鼠标输入/鼠标离开时的类

  •  1
  • Ibrahim Azhar Armar  · 技术社区  · 7 年前

    我有以下使用ngFor的元素

    <span *ngFor="let picture of pictures; let i = index">
        <a target="_blank" href="{{picture.image}}" class="thumbnail-display image-overlay">
            <span class="overlay-icon hide">
                <i class="fa fa-file-image-o image-preview" [attr.data-url]="picture.image" aria-hidden="true"></i>
                <i class="fa fa-trash-o image-del" aria-hidden="true" data-params="{&quot;id&quot;:&quot;101&quot;, &quot;type&quot;:&quot;venue&quot;}" data-url="#"></i>
            </span>
            <img src="{{picture.thumb}}">
        </a>
    </span>
    

    我想删除 hide 上课 <span class="overlay-icon hide"> 在鼠标上输入事件,然后添加回 隐藏 类的鼠标离开事件。

    我尝试了以下方法

    <span [ngClass]="class[i]" (mouseover)="class[i]='overlay-icon'" (mouseout)="class[i]='overlay-icon hide'">
    

    它不工作,并抛出以下错误。

    ERROR TypeError: Cannot read property '0' of undefined
    

    有人能告诉我怎么做吗?

    非常感谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   jo_va    7 年前

    也许您可以不使用数组,只需记住悬停范围的索引即可:

    <a (mouseover)="hoverIdx = i" (mouseout)="hoverIdx = -1">
        <span [ngClass]="{ 'overlay-icon': true, 'hide': hoverIdx !== i }">
        </span>
    </a>
    

    hoverIdx 初始化为-1,就不会出现数组索引问题。另外,您不必创建一个长度合适的数组并对其进行初始化。

    为了避免任何闪烁问题,请将悬停处理程序放置在父元素上,因为子元素处于打开/关闭状态。

    Stackblitz demo