2017-10-16 164 views
1

我有一個html項目(div),我想在mouseEnter上添加一個類並在mouseLeave上刪除它(添加另一個)。我有我的HostListeners用的mouseenter /鼠標離開行動的工作,但我的問題是如何訪問我的HTML元素,並添加/刪除類..訪問HostListener的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; 
} 

有了這個代碼,我得到:

"Property 'elementRef' does not exist on type 'NavigationViewMenuItemComponent'"

現在我明白「這個」是指我的ts元素,而不是html的,但我怎麼能從我的hostListener中訪問div元素?有任何想法嗎?

回答

0

沒有(this.relementRef as Element)....

也許你的意思是

evt.target.class 

,但它會被投注到使用角度綁定更新類。

@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; 
} 
+0

你需要投'(evt.target爲元素).classList.add(...)'或類似 –

+0

隨着hostBinding我得到這個:「錯誤:@HostBinding參數應該是一個屬性名, 'class。',或'attr。'。「 –

+0

對不起,'@HostBinding(...)'中的'[]'是多餘的。 –