2017-04-19 36 views
0

我从angular.js切换到angular2/4和无法理解我应该如何实现以下模式...角* ngFor方法的mouseenter

<div *ngFor="let item of items" (mouseenter)="focus=true" (mouseleave)="focus=false"> 

    <span>{{text}}</span> 

    <i *ngIf="focus" class="fa fa-pencil" aria-hidden="true"></i> 

</div> 

在Angular.js一focus标志是为ng-for 的每个元素迭代创建的,但在Angular中,focus标志对所有迭代的div都是全局的,导致当鼠标进入单个div时显示所有铅笔图标。

我很困惑我如何复制旧的Angular.js功能?

(我已经“解决”这个临时使用的子组件对于每次迭代,但是,这似乎是一锤子的办法,特别是如果代码是非常小的... ...线在哪里画?)

谢谢 西蒙价格

+0

你试过设置'item.focus'而不是'focus'吗? –

+0

是的,这是我的第一种方法,但它看起来很脏,装饰视图标志的数据项。 – SimonPriceUk

回答

0

我认为这种方法是过度复杂的问题,因为有一个更简单的选项,不涉及JavaScript。

首先添加几个类所涉及的两个元素(parentchild在这种情况下,但可用于任何东西,我们以后可以用它来选择它们):

<div *ngFor="let item of items" class="parent"> 
    <span>{{text}}</span> 
    <i class="fa fa-pencil child" aria-hidden="true"></i> 
</div> 

然后你可以使用CSS来使铅笔出现/消失,具体取决于鼠标是否悬停该项目。

.parent .child { 
    display: none; 
} 

.parent:hover .child { 
    display: inline; 
} 

这可以缩短为以下,取决于需要什么样的浏览器要支持(见this overview)。

.parent:not(:hover) .child { 
    display: none; 
} 
0

你可以这样做。

<div *ngFor="let item of items" (mouseenter)="item.focus=true" (mouseleave)="item.focus=false"> 

    <span>{{text}}</span> 

    <i *ngIf="item.focus" class="fa fa-pencil" aria-hidden="true"></i> 

</div> 
+0

查看以上评论 – SimonPriceUk

+0

那么如果您使用单个变量,那么您将如何确定哪个div受关注。你不能这样做。 – RemyaJ