今日Angularでホバーイベントを使ったので書いていきたいと思います
// app.component.html
.........
.........
<ng-template ngFor let-hero [ngForOf]="array" let-i="index">
<ul class="item-list">
<li>
<div class="status" *ngIf="hero.status === 1">
<div class="notice" (mouseout)="hoverOut()" (mouseover)="hoverIn(i)">
お買い得
</div>
<span *ngIf="hoverIndex == i">{{ hero.priceRate }}円お得</span>
</div>
{{hero.name}}
</li>
<li>{{hero.price}}円</li>
<li>{{hero.address}}</li>
</ul>
</ng-template>
</div>
// app.component.ts
.........
.........
export class AppComponent {
hoverIndex: number;
array = [
{
id: 0,
status: 1,
name: "スイカ",
price: 1200,
address: "群馬県",
priceRate: 240
},
{
id: 1,
status: 1,
name: "リンゴ",
price: 120,
address: "青森県",
priceRate: 40
}
];
hoverIn(id) {
this.hoverIndex = id;
}
hoverOut() {
this.hoverIndex = null;
}
}
let-i="index"を使用して配列の中身の順番を取得しそれらをiで出力します。
hoverInの引数にiを入れていきます。
hoverInメソッドはhoverIndexにiを代入して、arrayに割り振られた番号が一致した際に任意のpriceRateを出力するようになっています。
hoverOutはhoverIndexをnullにすることにより、priceRateを非表示にしています。