首页 > 解决方案 > 如何在 ngStyle 中为特定项目使用 ngFor 索引?

问题描述

我有这些代码行

<div class="picture"
           *ngFor="let item of data?.slice(0, data.length / 3); index as i">
        <div class="shadow"
             (mouseenter)="showShadow()"
             (mouseleave)="hideShadow()"
             [ngStyle]="{'background-color': shadow}">
          <img src="{{item.urls.small}}" alt="">
        </div>
      </div>

它工作正常,但问题是我无法解决如何使特定的阴影可见div,而不是在鼠标进入时对所有这些都可见。就像它在unsplash上的实现方式一样

TS文件

shadow = 'rgba(0, 0, 0, 0)';

showShadow(): void {
    this.shadow = 'rgba(0, 0, 0, 0.3)';
  }

  hideShadow(): void {
    this.shadow = 'rgba(0, 0, 0, 0)';
  }

如果有人需要,还有 SCSS 文件

.picture {
      margin: 8px;

      .shadow {
        position: relative;
        width: inherit;
        height: inherit;

        img {
          position: relative;
          z-index: -1;
        }
      }
    }

标签: angularngforng-style

解决方案


指令在这里是你的朋友。这是Attribute Directives的典型用例。而不是使用[ngStyle]and (mouseenter), (mouseleave), 使用指令。

所述指令类看起来像这样。(照原样从 Angular 文档复制)。

指示

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) { }

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

你的元素是:

<div appHighlight>
    <img ..... >
</div>

推荐阅读