在Angular 2中使用@HostBinding的模板子元素上的mouseenter / mouseleave时更改主机类

时间:2017-02-27 13:45:07

标签: angular angular2-directives angular2-hostbinding

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

在template.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;
}

1 个答案:

答案 0 :(得分: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);
}