单击某些其他链接时如何删除类并关闭子菜单

时间:2019-06-15 05:56:30

标签: angular

当用户单击具有子菜单的菜单时,会添加

菜单打开和活动类。

当用户单击另一个(例如此处的“我的个人资料”路线)时,我试图删除这两个类并关闭子菜单。

<li class="treeview" routerLinkActive="li-bg" [routerLinkActiveOptions]="{exact: true}">
    <a routerLink="/dashboard/my-profile">
      <i class="fa fa-user ic"></i><span class="d-title">My Profile</span>
    </a>
  </li>

  <!-- admin -->
  <li *ngIf="isAdmin" [ngClass]="{'li-bg':adminLinkHighlight()}"
  #myLi class="treeview" (click)="myLi.classList.toggle('menu-open'); myLi.classList.toggle('active');">
      <a style="cursor: pointer;">
          <i class="fa fa fa-shield ic"></i> <span class="d-title">&nbsp;&nbsp;Admin Options</span>
          <span class="pull-right-container">
            <i class="fa fa-angle-left pull-right"></i>
          </span>
      </a>
        <!-- <ul class="treeview-menu"> -->
        <ul (click)="$event.stopPropagation()" class="treeview-menu">
            <li style="cursor: pointer;"><a routerLink="/dashboard/files">&nbsp;&nbsp;&nbsp; Files</a></li>
        </ul>
        <ul (click)="$event.stopPropagation()" class="treeview-menu">
          <li style="cursor: pointer;" (click)="navigatToUsers();"><a>&nbsp;&nbsp;&nbsp;Users</a></li>
      </ul>

</li>

1 个答案:

答案 0 :(得分:0)

我已经使用@Hostlistener解决了这个问题。下面是我的个人参考代码,这里是StackBlitz

@HostListener('document:click', ['$event']) onClick(event: MouseEvent) {
    // event contains all methods and DOM objects of the clicked element
    console.log(event);

    // event.target returns the node that was targeted by the function. 
    // This means you can work with the node like one you'd get from document.getElementById
    console.log(event.target);

    // Using target’s methods sometimes require typing the targetted element: 
    // `(<ElementType>event.target).METHOD`
    console.log((<HTMLElement>event.target).querySelector('input'));// TS error
    console.log((<HTMLElement>event.target).querySelector('p')); // TS works

    // get a node list of all elements with .class-name
    console.log(this.eRef.nativeElement.querySelectorAll('.class-name'));


    // 1. log clicking any elements within a parent component from this child component
    // 2. log clicking anywhere outside the parent component
    if (this.eRef.nativeElement.parentNode.contains(event.target)) {
      this.area = 'Clicked any element within parent component: (' + (<HTMLElement>event.target).tagName + ')';
    } else if(!this.eRef.nativeElement.parentNode.contains(event.target)) {
      this.area = 'Clicked outside parent component: (' + (<HTMLElement>event.target).tagName + ')';
    } else {
      this.area = 'Clicked parent component: (' + (<HTMLElement>event.target).tagName + ')';
    }
}

您可以在组件,指令或管道中使用@Hostlistener

使用Renderer2

正确添加和删除类
renderer.addClass(hostElement.nativeElement, 'class-name');

renderer.removeClass(hostElement.nativeElement, 'class-name');