【问题标题】:Angular | How to define a template variable for a div角 |如何为 div 定义模板变量
【发布时间】:2019-11-11 14:33:40
【问题描述】:

以下代码生成 4 个 200x200 的 div。

我想在鼠标悬停时将一个类设置为一个div(该类应该只设置为悬停的div,而不是其他三个)

<style>
   div {height: 200px; width: 200px; margin: 20px;}
   .mouseover {background-color: red;}
</style>

<div *ngFor="let a of [1,2,3,4]" 
    [class.mouseover]="mouseOvered" 
    (mouseover)="mouseOvered=true" 
    (mouseleave)="mouseOvered=false">
</div>

在组件中不定义mouseOvered怎么办?

【问题讨论】:

  • 如果您只是想简化或编写更少的代码,您可以在指令中隔离此逻辑 - 尽管我认为您所拥有的一切都很好
  • 上述解决方案的问题是,如果单个 div 悬停,所有 div 都会获得类 'mouseover'。我认为您对创建自定义指令是正确的。

标签: angular


【解决方案1】:

我建议创建一个指令来隔离ngFor 中的每个实例:

@Directive({
  selector: '[mouseOver]'
})
export class MouseOverDirective {

  @HostBinding('class.mouseover')
  isMouseOver = false;

  @HostListener('mouseenter')
  onEnter() {
    this.isMouseOver = true;
  }

  @HostListener('mouseleave')
  onLeave() {
    this.isMouseOver = false;
  }
}

并按如下方式使用:

<div *ngFor="let a of [1,2,3,4]" mouseOver></div>

StackBlitz Example

另类

如果你不想创建指令,你也可以使用索引映射来存储每个实例的条件:

组件类:

export class MyExampleComponent  {

  mouseOvered: { [index: number]: boolean } = {};

}

组件模板:

<div *ngFor="let a of [1,2,3,4]; let i = index" 
    [class.mouseover]="mouseOvered[i]" 
    (mouseover)="mouseOvered[i]=true" 
    (mouseleave)="mouseOvered[i]=false">
</div>

StackBlitz Example

【讨论】:

    【解决方案2】:

    纯 css 解决方案,基于您的代码:

    div {
      height: 200px; 
      width: 200px; 
      margin: 20px;
      background-color: orange;
    }
    
    div:hover {
      background-color: red;
    }
    

    Stackblitz.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 2020-03-08
      相关资源
      最近更新 更多