1

Is there a way to use @HostBinding dynamically when we trigger mouseeneter/mouseleave event on child element in a template, that is:

in template.component.html

<div class="test-btn"
   (mouseenter)="mouseenter()"
   (mouseleave)="mouseleave()">
</div>

and in template.component.ts

@HostBinding('class') classes = this.getMouseClass();

where:

private getStateClass() {
    const mouse = this.mouseState ? 'mouse-enter' : 'mouse-leave';
    return `${mouse}`;
}

mouseenter() {
    this.mouseState = true;
}

mouseleave() {
    this.mouseState = false;
}

1 Answers1

0

You can only add/remove static classes with @HostBinding()

@HostBinding('class.myclass')
mouseState = false;

mouseenter() {
    this.mouseState = true;
}

mouseleave() {
    this.mouseState = false;
}

If you need dynamic classes, you can inject ElementRef and add/remove the class imperatively

constructor(elRef:ElementRef) {}

private setStateClass(bool add) {
  this.elRef.nativeElement.classList.add('mouse-enter', add);
  this.elRef.nativeElement.classList.add('mouse-leave', !add);
}

mouseenter() {
    this.setStateClass(true);
}

mouseleave() {
    this.setStateClass(false);
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567