将鼠标悬停在NgClass上

时间:2019-02-21 18:42:14

标签: html css angular ng-class

我正在尝试使用Angular ngClass指令对div进行悬停效果。在模板文件中,我有一个div元素,其类别为“ list-item-container”,其中包含一个div,其类别为“ list-item”,并通过一个* ngFor指令进行了迭代。具有“ list-item-column”类的div像带有行内显示的表行一样水平放置。在具有“ list-item”类的div中,我已经放置了mouseenter和mouseleave事件侦听器,它们在我的.ts中调用了hoverListItem() hoverListItem()函数将listItemHovered变量的值更改为true或false在“ list-item”类中,我有一个ngClass指令,该指令根据listItemHovered布尔值触发css类“ list-item-highlight”值,然后将背景更改为其他颜色。

我面临的问题是,将鼠标指针悬停在“ list-item” div上时,我所有的“ list-item” div都会受到影响,而不是我正在悬停的那个div上。如何解决这个问题?

.html文件

<div class="list-item-container">
      <ng-container *ngFor="let opportunity of dealService.opportunities">
        <div [ngClass]="{'list-item-highlight': listItemHovered}" class="list-item" (mouseenter)="hoverListItem()"
             (mouseleave)="hoverListItem()"
             (click)="selectOpportunity(opportunity)">
          <div
            class="list-item-column">{{opportunity.account?.name === null ? "N/A" : opportunity.account.name}}</div>
          <div class="list-item-column">{{opportunity.requirementTitle}}</div>
          <div class="list-item-column">{{opportunity.salesValue | number: '1.0-2'}}</div>
        </div>
      </ng-container>
    </div>

.css文件

.list-item-container{
  overflow: auto;
  width: 100%;
  max-height: 500px;
}
.list-item{
  font-size: 15px;
  border-radius: 10px ;
  margin-top: 5px;
  height: 50px;
  background: lightgray;
  color: black;
}

.list-item-highlight{
  background: #7e00cc;
  color: white;
}

.list-item-column{
  height: inherit;
  vertical-align: center;
  display: inline-block;
  width: 33.33%;
  padding-left: 40px;
}

.ts文件

 hoverListItem() {
    this.listItemHovered = !this.listItemHovered;
  }

2 个答案:

答案 0 :(得分:2)

现在,您正在组件上下文中创建和修改listItemHovered标志,而应该为每个项目级别维护一个标志,这可以帮助轻松地识别是否已突出显示小麦组件。

[ngClass]="{'list-item-highlight': opportunity.listItemHovered}"
(mouseenter)="hoverListItem(opportunity)"
(mouseleave)="hoverListItem(opportunity)"

组件

hoverListItem(opportunity) {
   opportunity.listItemHovered = !opportunity.listItemHovered;
}

尽管如果要求只是突出显示悬停元素,我建议使用:hover伪类。通过更改CSS规则可以很容易地做到这一点。这样可以节省多个变更检测周期以供运行。

.list-item:hover {
  background: #7e00cc;
  color: white;
}

答案 1 :(得分:1)

我建议使用directive来监听目标元素上的悬停事件并附加该类:

@Directive({
    selector: '[hoverDir]'
})


 export class HoverOverDirective { 
    @HostListener('mouseenter') onMouseEnter() {
       this.elementRef.nativeElement.class = 'list-item-highlight';
    }

     @HostListener('mouseleave') onMouseLeave() {
       this.elementRef.nativeElement.class = 'list-item-not-highlight';
     }
}

或者最简单的方法是利用CSS pseudo property :hover并按以下方式使用它:

.list-item:hover {
  background: #7e00cc;
  color: white;
}  
相关问题