【问题标题】:Access HTML element from HostListener从 HostListener 访问 HTML 元素
【发布时间】:2024-01-09 18:54:02
【问题描述】:

我有一个 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;
}

使用此代码,我得到:

“类型上不存在属性‘elementRef’ 'NavigationViewMenuItemComponent'"

现在我知道“this”指的是我的 ts 元素,而不是 html 元素,但是如何从我的 hostListener 中访问 div 元素?有什么想法吗?

【问题讨论】:

    标签: html css angular typescript


    【解决方案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;
    }
    

    【讨论】:

    • 你需要投(evt.target as Element).classList.add(...)或类似的
    • 使用 hostBinding 我得到这个:“错误:@HostBinding 参数应该是一个属性名称,'class.' 或 'attr.'。”
    • 抱歉,@HostBinding(...) 中的 [] 是多余的。