1

当我们在模板中的子元素上触发 mouseeneter/mouseleave 事件时,有没有办法动态使用@HostBinding,即:

在模板.component.html

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

并在 template.component.ts

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

在哪里:

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

mouseenter() {
    this.mouseState = true;
}

mouseleave() {
    this.mouseState = false;
}
4

1 回答 1

0

您只能添加/删除静态类@HostBinding()

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

mouseenter() {
    this.mouseState = true;
}

mouseleave() {
    this.mouseState = false;
}

如果您需要动态类,则可以ElementRef命令式地注入和添加/删除该类

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);
}
于 2017-02-27T13:49:11.633 回答