Celebes
Celebes

Reputation: 1431

Adding html class attribute conditionally on hover

I want to add a class to table row on hover. I know I can add classes like this:

<tr [class.info]="isMyConditionTrue()"></tr>

and "info" class will be added when my condition is true. But how do I check if my table row is hovered? I could set some inner variable in typescript to true on (mouseenter) and to false on (mouseleave), but it's problematic if I have alot of rows generated by *ngFor. I'd have to create another component for each row or store them in some hashtable. Is there a way to achieve this just by using something like <tr #row [class.info]="row.hovered"></tr>?

Upvotes: 3

Views: 621

Answers (1)

drew moore
drew moore

Reputation: 32680

@Component({
  selector: 'hover-info'
  template: `<tr [class.info]="isHovered$ | async"></tr>
})
class HoverRow { 

   _hovers$: Subject<boolean> = BehaviorSubject.create(); 
   isHovered$: Observable<boolean> = this._hovers$.last();

   @HostListener('mouseover') onMouseover = () => this._hovers$.next(true); 
   @HostListener('mouseout') onMouseout = () => this._hovers$.next(false); 

} 

AsyncPipe is a powerful thing.

Note that there's an open proposal for a feature that would simplify the boilerplate needed here. I doubt it'll land before release but expect it will soon thereafter.

Upvotes: 1

Related Questions