angular - 如何在 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;
}
}
}
解决方案
指令在这里是你的朋友。这是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>
推荐阅读
- php - PHP SQL Server连接工作或不工作
- reactjs - 改进对 React 的错误处理 | 还原 | MERN 应用程序
- html - XSLT:如何避免在 HTML 的属性中添加自闭合标签
- c - 从函数返回多个错误之一并在 C 中结束程序的最佳实践是什么?
- ios - 等到应用内购买完成,直到执行操作
- css - 从底部绝对定位不创建溢出滚动条
- ssl - wso2 apim 1.10.0 SSL 通信
- typescript - 打字稿声明:模块检测和命名空间
- javascript - 更改从文本文件读取的 js 文件的样式
- redux - Redux saga:redux-saga 工作原理的内部结构