当我们在模板中的子元素上触发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;
}
答案 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);
}