带有href的简单锚标记会导致Angular页面刷新

问题描述 投票:0回答:1

我有一个Web组件,该组件使用简单的锚标记和带有指向路径的href。

单击链接后,将重新加载应用程序。

我无法使用routerLink(Web组件不是Angular)。避免页面重新加载的最佳方法是什么?

angular href router web-component
1个回答
0
投票

要解决此问题,我会监听“ a”标签的点击,如果它不包含“ routerlink”属性,则会阻止默认行为。

  @HostListener('window:click', ['$event'])
  onClick(e: any) {
    const path = e.composedPath() as Array<any>;
    const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
    if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
      const href = firstAnchor.getAttribute('href');

      this.router.navigateByUrl(href);

      e.preventDefault();
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.