Search code examples
angularmouseenterngforangular-ng-if

Angular *ngFor approach for scoped flags set by mouseenter


I am switching from angular.js to angular2/4 and have trouble understanding how I should implement the following pattern ...

<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>

In Angular.js a focus flag was created for each element iteration of the ng-for but in Angular, the focus flag is global to all iterated div resulting in all pencil icons being displayed when the mouse enters a single div.

I am confused as to how I could replicate the old Angular.js functionality ?

(I have "solved" this temporarily by using child components for each iteration, however, this seems like a hammer approach especially if the code is very small... where is the line drawn ?)

Thanks Simon Price


Solution

  • I think the approach is overcomplicating the issue as there is a simpler option that doesn't involve javascript.

    First add a couple of classes to the two elements that are involved (parent and child in this case, but anything that we can use later on to select them can be used):

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

    Then you can use CSS to make the pencil appear/disappear depending on whether the mouse hovers the item.

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

    This could be shortened to the following, depending on what kind of browsers need to be supported (see this overview).

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