在 ngFor 中切换 class 鼠标进入/鼠标离开
Toggle class on mouse-enter / mouse-leave in ngFor
我有以下使用 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="{"id":"101", "type":"venue"}" data-url="#"></i>
</span>
<img src="{{picture.thumb}}">
</a>
</span>
我想在 <span class="overlay-icon hide">
中删除鼠标进入事件中的 hide
class,并在鼠标离开事件中添加 hide
class。
我尝试了以下方法
<span [ngClass]="class[i]" (mouseover)="class[i]='overlay-icon'" (mouseout)="class[i]='overlay-icon hide'">
它不起作用,并抛出以下错误。
ERROR TypeError: Cannot read property '0' of undefined
谁能指出我该怎么做?
谢谢。
也许你可以在没有数组的情况下做到这一点,只需要记住悬停范围的索引:
<a (mouseover)="hoverIdx = i" (mouseout)="hoverIdx = -1">
<span [ngClass]="{ 'overlay-icon': true, 'hide': hoverIdx !== i }">
</span>
</a>
这样你只需要一个初始化为 -1 的变量 hoverIdx
,你就不会遇到数组索引问题。此外,您不必创建适当长度的数组并对其进行初始化。
为避免任何闪烁问题,请将悬停处理程序放在父元素上,因为子元素会切换 on/off。
Here is a Stackblitz demo
我有以下使用 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="{"id":"101", "type":"venue"}" data-url="#"></i>
</span>
<img src="{{picture.thumb}}">
</a>
</span>
我想在 <span class="overlay-icon hide">
中删除鼠标进入事件中的 hide
class,并在鼠标离开事件中添加 hide
class。
我尝试了以下方法
<span [ngClass]="class[i]" (mouseover)="class[i]='overlay-icon'" (mouseout)="class[i]='overlay-icon hide'">
它不起作用,并抛出以下错误。
ERROR TypeError: Cannot read property '0' of undefined
谁能指出我该怎么做?
谢谢。
也许你可以在没有数组的情况下做到这一点,只需要记住悬停范围的索引:
<a (mouseover)="hoverIdx = i" (mouseout)="hoverIdx = -1">
<span [ngClass]="{ 'overlay-icon': true, 'hide': hoverIdx !== i }">
</span>
</a>
这样你只需要一个初始化为 -1 的变量 hoverIdx
,你就不会遇到数组索引问题。此外,您不必创建适当长度的数组并对其进行初始化。
为避免任何闪烁问题,请将悬停处理程序放在父元素上,因为子元素会切换 on/off。
Here is a Stackblitz demo