Angular 检测点击组件内的任何链接

Angular detect Click on any of the Links inside a component

我有一个自定义 side-nav 组件。

哪个可以用link这个:

<button (click)="sideNav.open()">Menu</button>

<side-nav #sideNav>
    <a routerLinkActive="active" routerLink="/">Home</a>
    <a routerLinkActive="active" routerLink="/products">Products</a>
    <a routerLinkActive="active" routerLink="/about">About</a>
    <a routerLinkActive="active" routerLink="/contact">Contact</a>
</side-nav>

单击“菜单”按钮可打开包含 side-nav 标签内内容的侧边导航。

我想在用户点击任何 link 时自动关闭侧边导航。

任何人都可以指导如何为我的 SideNavComponent 中的所有 links(和按钮)添加一个点击处理程序,自动关闭 'side-nav'

下面是我的组件:

import { Location } from "@angular/common";
import { Component, Input, Renderer2 } from '@angular/core';

@Component({
  selector: 'side-nav',
  templateUrl: './side-nav.component.html'
})
export class SideNavComponent {

  @Input() isOpen: boolean = false;
  @Input() enabled: boolean = true;
  @Input() extraClasses: string = '';
  
  constructor(private location: Location,
    private renderer: Renderer2) {
  }

  ngOnInit() {
  }

  open() {
    this.isOpen = true;
    window.addEventListener('popstate', this.onHardwareBackButton, { passive: true });
    this.location.go('side-nav');
    this.renderer.addClass(document.body, 'noscroll');
  }

  close(goBack: boolean = false) {
    this.isOpen = false;
    window.removeEventListener('popstate', this.onHardwareBackButton);
    this.renderer.removeClass(document.body, 'noscroll');
    if (goBack) {
      window.history.back();
    }
  }

  onHardwareBackButton = () => {
    this.close();
    window.removeEventListener('popstate', this.onHardwareBackButton);
  };
}

模板

<ng-container *ngIf="enabled">
  <nav id="sidebar-nav" [swipe]="true" (swipeLeft)="close(true)" [ngClass]="{'close':!isOpen,'open':isOpen}" class="{{extraClasses}}">
    <ng-container *ngTemplateOutlet="contentTpl"></ng-container>
  </nav>
  <div id="nav-screen-overlay" (click)="close(true)"></div>
</ng-container>

<ng-container *ngIf="!enabled">
  <ng-container *ngTemplateOutlet="contentTpl"></ng-container>
</ng-container>

<ng-template #contentTpl><ng-content></ng-content></ng-template>

我知道我可以在所有 link 上添加 (click)="sideNav.close()",但我想在用户点击任何可点击项目时自动执行此操作,例如links 或按钮。

你可以试试这个,但我想知道为什么你不能简单地在 html 本身添加 click 事件,如果重复是你的问题然后创建一个链接数组和循环(ngFor ) 它。

allListeners: (() => void)[] = [];
constructor(private elementRef: ElementRef, private renderer: Renderer2) {}

ngAfterViewInit() {
    const myComponent = this.elementRef.nativeElement as HTMLElement;
    const clickableElements = myComponent.querySelectorAll("a, button");
    clickableElements.forEach(eachElem => {
      const listener = this.renderer.listen(eachElem, "click", () => {
        console.log("Element clicked"); //Close sidenav
      });
      this.allListeners.push(listener);
    });
}

ngOnDestroy() {
    //Remove click listeners
    this.allListeners.forEach(listener => listener())
}