Joe Fisher
Joe Fisher

Reputation: 117

Access HTML element from HostListener

I have an html item (div), which I want to add a class to on mouseEnter and remove it (add another one) on mouseLeave. I have my HostListeners working with the mouseenter/mouseleave actions, but my problem is how to access my html element and add/remove the classes..

item.html

<div clrDropdownItem class="hidden-action">
    <span class="vui-icon" [ngClass]="menuItem.icon"></span>
    <span [textContent]="menuItem.title"></span>
</div> 

item.component.ts

@Component({
           selector: 'vsc-navigation-view-menu-item',
           templateUrl: './navigation-view-menu-item.html',
           changeDetection: ChangeDetectionStrategy.OnPush
        })
    export class NavigationViewMenuItemComponent {
           @Input() menuItem: NavigatorNodeSchema;

       constructor(@Inject(forwardRef(() => NavigationViewMenuComponent)) public menuComponent: NavigationViewMenuComponent, private navigationService: NavigationService) {

       }
    @HostListener('mouseenter', ['$event'])
       onMouseEnter(evt: MouseEvent) {
          if(evt.ctrlKey){
              this.elementRef.nativeElement.class = 'remove-action';
          }
           console.log(this.menuItem.navigationTargetUid);
       }

    @HostListener('mouseleave', ['$event'])
    onMouseLeave(evt: MouseEvent) {
            this.elementRef.nativeElement.class = 'hidden-action';
    }
}

item.css

.hidden-action {
  text-decoration: none !important;
}

.remove-action {
  text-decoration: line-through !important;
  text-decoration-color: red !important;
}

With this code I get:

"Property 'elementRef' does not exist on type 'NavigationViewMenuItemComponent'"

Now I get that "this" is refering to my ts element, not the html one, but how can I access the div element from within my hostListener? Any ideas?

Upvotes: 2

Views: 2412

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657761

There is no (this.relementRef as Element)....

Perhaps you meant

evt.target.class

but it would be betting to use Angular bindings to update classes.

@HostBinding('class.remove-action')
isRemoveAction = false;

@HostBinding('class.hidden-action')
isHiddenAction = false;

@HostListener('mouseenter', ['$event'])
   onMouseEnter(evt: MouseEvent) {
      if(evt.ctrlKey){
          this.isRemoveAction = true;
      }
       console.log(this.menuItem.navigationTargetUid);
   }

@HostListener('mouseleave', ['$event'])
onMouseLeave(evt: MouseEvent) {
   this.isHiddenAction = true;
}

Upvotes: 1

Related Questions