i have a comment component with a mat-list component from material and inside it many mat-item-list so for each mat-list-item component i want to listen event like mouseenter and do something when event is happening.
This is the template of the component
@if(comments.length !== 0){
<mat-list>
<h2 mat-subheader>Commentaires </h2>
@for (comment of comments; let i = $index; track $index) {
<mat-list-item animateList>
<span matListItemTitle>{{ comment.comment }}</span>
<span matListItemLine>{{ comment.createdDate | timeAgo }}</span>
</mat-list-item>
}
</mat-list>
}
I create a directive for it to listen the event on it
import { AfterViewInit, Directive, ElementRef, HostListener, inject, Renderer2 } from '@angular/core';
@Directive({
selector: '[animateList]'
})
export class AnimateList {
//dependency injection
el = inject(ElementRef);
render = inject(Renderer2);
//adding event
@HostListener('mouseenter')
onMouseEnter() {
this.render.addClass(this.el.nativeElement, 'active');
}
@HostListener('mouseleave')
onMouseLeave() {
this.render.removeClass(this.el.nativeElement, 'active');
}
}
and here is the animation that i want
.active{
animation: scale-colored 300ms ease-in;
}
@keyframes scale-colored {
from {
background-color: white;
transform: scale(1);
z-index: 1;
}
to {
background-color: rgb(147, 150, 242);
transform: scale(1.05);
z-index: 2;
}
}
:hovercss pseudoclass. it is and simpler and more error prone and more resources efficient