Angular 如何在特定项目的ngStyle中使用ngFor索引?
我有这些代码行Angular 如何在特定项目的ngStyle中使用ngFor索引?,angular,ngfor,ng-style,Angular,Ngfor,Ng Style,我有这些代码行 <div class="picture" *ngFor="let item of data?.slice(0, data.length / 3); index as i"> <div class="shadow" (mouseenter)="showShadow()" (mouseleave)=
<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>
如果有人需要,也可以使用SCSS文件
.picture {
margin: 8px;
.shadow {
position: relative;
width: inherit;
height: inherit;
img {
position: relative;
z-index: -1;
}
}
}
我是你的朋友。这是的一个典型用例。 使用指令而不是使用
[ngStyle]
和(mouseenter)
,(mouseleave)
所述指令类将如下所示。(按原样从角度文档复制)
指示
你的元素是:
<div appHighlight>
<img ..... >
</div>
萨钦给出了一个很好的方法。但我想我应该指出,在您当前的方法中,将[ngStyle]=“{'background-color':shadow}”
放在div
上意味着阴影的背景色将始终应用于div
上,无论鼠标在哪里,由于没有附加到何时应用“背景色”的条件:阴影
向TS文件中添加一个布尔值
,如下所示
shouldShowShadow: boolean = false; // I know this variable name is a mouthful, but it's all I could think of off the top of my head.
shadow = 'rgba(0, 0, 0, 0)';
showShadow(): void {
this.shadow = 'rgba(0, 0, 0, 0.3)';
this.shouldShowShadow = true;
}
hideShadow(): void {
this.shadow = 'rgba(0, 0, 0, 0)';
this.shouldShowShadow = false;
}
并在ngStyle
中使用它,通过执行以下操作来确定何时显示阴影
<div class="shadow"
(mouseenter)="showShadow()"
(mouseleave)="hideShadow()"
[ngStyle]="{'background-color': shouldShowShadow ? 'shadow' : 'transparent'}">
<img src="{{item.urls.small}}" alt="">
</div>
应该有用
shouldShowShadow: boolean = false; // I know this variable name is a mouthful, but it's all I could think of off the top of my head.
shadow = 'rgba(0, 0, 0, 0)';
showShadow(): void {
this.shadow = 'rgba(0, 0, 0, 0.3)';
this.shouldShowShadow = true;
}
hideShadow(): void {
this.shadow = 'rgba(0, 0, 0, 0)';
this.shouldShowShadow = false;
}
<div class="shadow"
(mouseenter)="showShadow()"
(mouseleave)="hideShadow()"
[ngStyle]="{'background-color': shouldShowShadow ? 'shadow' : 'transparent'}">
<img src="{{item.urls.small}}" alt="">
</div>