我有一个html项目(div),我想在mouseEnter上添加一个类并在mouseLeave上删除它(添加另一个)。我的HostListeners使用了mouseenter / mouseleave操作,但我的问题是如何访问我的html元素并添加/删除类..
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;
}
使用此代码我得到:
&#34; Property&#39; elementRef&#39;在类型上不存在 &#39; NavigationViewMenuItemComponent&#39;&#34;
现在我明白这个&#34;这个&#34;引用我的ts元素,而不是html元素,但是如何从hostListener中访问div元素?有什么想法吗?
答案 0 :(得分:1)
没有(this.relementRef as Element)....
也许你的意思是
evt.target.class
但它会打赌使用Angular绑定来更新类。
@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;
}